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:
(20 < temp) && (temp <= 30)
, since it appears in the else-branch of
the first condition. Hence, we already know that (temp <= 30) is
true.