DEV Community

Cover image for Nested if and Multi-Way if-else Statements
Paul Ngugi
Paul Ngugi

Posted on

Nested if and Multi-Way if-else Statements

An if statement can be inside another if statement to form a nested if statement. The statement in an if or if-else statement can be any legal Java statement, including another if or if-else statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following is a nested if statement:

if (i > k) {
if (j > k)
 System.out.println("i and j are greater than k");
}
else
 System.out.println("i is less than or equal to k");
Enter fullscreen mode Exit fullscreen mode

The if (j > k) statement is nested inside the if (i > k) statement. The nested if statement can be used to implement multiple alternatives. The statement given in figure (a) below, for instance, prints a letter grade according to the score, with multiple alternatives. A preferred format for multiple alternatives is shown in (b) using a multi-way if-else statement.

Image description

The execution of this if statement proceeds as shown above. The first condition (score >= 90.0) is tested. If it is true, the grade is A. If it is false, the second condition (score >= 80.0) is tested. If the second condition is true, the grade is B. If that condition is false, the third condition and the rest of the conditions (if necessary) are tested until a condition is met or all of the conditions prove to be false. If all of the conditions are false, the grade is F. Note that a condition is tested only when all of the conditions that come before it are false.

Image description

This style, called multi-way if-else statements, avoids deep indentation and makes the program easy to read.

Top comments (0)