next up previous
Next: Example: type of a Up: Unit 05 Previous: Nested if's with mutually

Ambiguity of the else in if-else statements

Consider the following code fragment:

if (a > 0) if (b > 0) System.out.println("b positive");
else System.out.println("???");

System.out.println("???") could in principle be the else-branch of:

The ambiguity is solved by considering that an else always refers to the nearest if without an associated else. In the above example we have:

if (a > 0)
  if (b > 0)
    System.out.println("b positive");
  else
    System.out.println("b negative");

It is always possible to use a block (i.e., {..}) to disambiguate nested if-else statements. In particular, if we want that an else refers to an if that is not the immediately preceding one, we have to enclose the immediately preceding if in a block. For example:

if (a > 0) {
  if (b > 0)
    System.out.println("b positive");
} else
  System.out.println("a negative");


next up previous
Next: Example: type of a Up: Unit 05 Previous: Nested if's with mutually