If Statement in Java Programming : Conditional Selection
Flow of If Statement
- The if statement is a conditional branch statement.
- It tells your program to execute a certain section of code only ' if ' a particular test evaluates to true.
- If boolean Expression evaluates to true, the statements in the block following the if statement are executed.
- If it evaluates to false, the statements in the if block are not executed.
Syntax : If Statement
if (boolean == true) {statement(s) // execute}
- If boolean Expression evaluates to false and there is an else block, the statements in the else block are executed.
Syntax : If-Else Statement
if (boolean == false) {statement(s)} else {statement(s) // execute}
Syntax : If - Else Ladder Statement
- If we have multiple conditions then we can use if-else ladder –
if (booleanExpression1) {// statements} else if (booleanExpression2) { // multiple coditions working in steps// statements}else { // statements}
Example 1 : Simple If-Else Ladder Statement
class IfExample {public static void main(String[] args) {int marks = 55; // marks is int holding integer 76String result; // result is String holding String in double quotationif (marks >= 40) { // condition is trueresult = "Pass"; // statement executed}if (marks < 40) {result = "Fail";}System.out.println("Result = " + result); // print line on console}}
Output :
Result = Pass
Example 2 : Simple If-Else Ladder Statement
class IfExample {public static void main(String[] args) {int marks = 35;String result;if (marks >= 40) { // false Statementresult = "Pass";}else{result = "Fail"; // executed}System.out.println("Result = " + result);}}
Output :
Result = Fail
Example 3 : Simple If-Else Ladder Statement
class IfElseExample {public static void main(String[] args) {int marks = 73;char result;if (marks >= 90) {result = 'A';} else if (marks >= 80) {result = 'B';} else if (marks >= 70) {result = 'C';} else if (marks >= 60) {result = 'D';} else {result = 'F';}System.out.println("Result = " + result);}}
Output :
Grade = C
Example 4 : Multiple conditions inside If
if(marks > 70 || marks < 90)System.out.println("Class A");elseSystem.out.println("Class B");
- We can use “&&” , “||” operators in order to refine condition.
- && operator will check whether both left hand and right hand conditions are true or not.
- || condition will check
IMPORTANT NOTE :
If we have written two conditions inside “If Condition” then –
- If First Condition is true then || operator will skip checking second condition.
- If First Condition is false then || operator will check second condition if second condition is true then overall if will follow true block otherwise it will follow else block.
Proof –
class Test{public static void main(String args[]){int number1 = 50;int number2 = 70;if ((++num1 > 0) || (++num2 > 0)){System.out.println(num1);System.out.println(num2);}}}
Output :
5070
Comments
Post a Comment