Curriculum
In Java, a nested if-else statement is a series of if-else statements that are nested inside one another. The inner if-else statements are executed based on the conditions of the outer if-else statements.
The basic syntax for a nested if-else statement is:
if (condition1) { // code block 1 if (condition2) { // code block 2 } else { // code block 3 } } else { // code block 4 }
In this syntax, the outer “if” statement checks the condition1, and the code block1 is executed if the condition1 is true. If the condition1 is false, then the code block4 is executed. If the condition1 is true, then the inner “if” statement checks condition2. If condition2 is true, then code block2 is executed. If condition2 is false, then code block3 is executed.
Here’s an example of a nested if-else statement in action:
int x = 5; int y = 10; if (x > 3) { if (y > 5) { System.out.println("x is greater than 3 and y is greater than 5"); } else { System.out.println("x is greater than 3 but y is less than or equal to 5"); } } else { System.out.println("x is less than or equal to 3"); }
In this example, the outer “if” statement checks if x is greater than 3. If it is, then the inner “if” statement checks if y is greater than 5. If both conditions are true, then the message “x is greater than 3 and y is greater than 5” is printed. If the first condition is true but the second condition is false, then the message “x is greater than 3 but y is less than or equal to 5” is printed. If the first condition is false, then the message “x is less than or equal to 3” is printed.