This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and rest will be bypassed.
If none of the conditions is true then the final else statement at the end will be executed.
Flowchart diagram for if-else if statement in java:
Syntax of if-else-if ladder statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | if(condition1) { //code to be executed if condition1 is true } else if(condition2) { //code to be executed if condition2 is true } else if(condition3) { //code to be executed if condition3 is true } ... else { //final esle if all the above condition are false } |
Example of nested-if statement in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class IfElseIfTest { public static void main(String args[]) { int num1 = 10, num2 = 20; if (num1 > num2) { System.out.println("num1 is greater"); } else if(num2 > num1){ System.out.println("num2 is greater"); } else { System.out.println("Both are same"); } } } |
Output:
1 | num2 is greater |