PREV NEXT
Java If then Else statement provides two paths. The if block is executed when the condition holds true. When the condition evaluates to false, the statements inside the else block are executed.
Syntax for Java If then Else :
if(condition)
{ //statements, when condition is true } else { //statements, when condition is false } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Class Great{ Public static void main(String args[]){ int a = 3, b = 5; if(a>b) { System.out.println(“a is greater than b”); } else { System.out.println(“b is greater than a”); } } |
Output:
b is greater than a |
In the above program, the statement inside the else block is executed since the condition a>b evaluates to false.
Else if statement:
We can also provide multiple conditions to be checked by using else if statement.
Example Else if statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
Class Grade { Public static void main(String args[]) { int marks = 88; if(marks > 89) { System.out.println(“Distinction”); } else if(marks >79) {System.out.println(“First class”); } else if(marks >69) {System.out.println(“Second class”); } else if(marks >49) {System.out.println(“Pass”); } else // executed when all the above conditions are false {System.out.println(“Fail”); } |
Output:
First class |
In the above program, the top most ‘if’ condition evaluates to ‘true’ and its statements are executed. Since this is evaluated to true, control will not go to check other else if conditions and last else block. otherwise the control keeps on shifting to the next else-if loop till any of its condition holds true. The last else block executes only when the if block and all the else-if blocks fails to execute.