Next: Ambiguity of the else Up: Unit 05 Previous: Nested if's

## Nested if's with mutually excluding conditions

A common use of nested if's is when the conditions in the nested if's are mutually excluding, i.e., no two of them can be simultaneously true.

Example: Based on the value of the temperature (an integer) print a message according to the following table:

 temperature t message 30 < t hot 20 < t < = 30 warm 10 < t < = 20 fine t < = 10 cold

```int temp;
...
if (30 < temp)
System.out.println("hot");
else if (20 < temp)
System.out.println("warm");
else if (10 < temp)
System.out.println("fine");
else
System.out.println("cold");
```

Observations:

• At the outermost level we have a single if-else statement.
• The order in which the conditions are specified is important.
• The second condition need not be composite, e.g., `(20 < temp) && (temp <= 30)`, since it appears in the else-branch of the first condition. Hence, we already know that (temp <= 30) is true.
• Each else refers to the if that immediately precedes it.

Next: Ambiguity of the else Up: Unit 05 Previous: Nested if's