Java nested if else Statement
In Java, the nested if-else statement allows you to create a more complex branching decision structure. It allows you to test multiple conditions, with each condition being dependent on the result of the previous condition.
Here is the basic syntax of the nested if-else statement in Java:
if (condition1) { if (condition2) { // code to execute if both condition1 and condition2 are true } else { // code to execute if condition1 is true and condition2 is false } } else { // code to execute if condition1 is false }
The inner if statement is executed only if the outer if statement is true. If the outer if statement is false, the else block is executed.
Here is an example that uses the nested if-else statement to check the grade of a student and print a message based on their grade and attendance:
int grade = 85; boolean isPresent = true; if (isPresent) { if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else { System.out.println("Fail"); } } else { System.out.println("Absent"); }
In this example, the program checks the value of the variable isPresent
and executes the nested if statement only if it's true. If isPresent
is true, the program checks the value of the variable grade
and prints a message based on its value. If grade
is 85 and isPresent
is true, the output will be "B", because the second condition (grade >= 80
) is true. If isPresent
is false, the output will be "Absent".