Nested conditionals

In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:

  if (x == 0) {
    System.out.println("x is zero");
  } else {
    if (x > 0) {
      System.out.println("x is positive");
    } else {
      System.out.println("x is negative");
    }
  }

There is now an outer conditional that contains two branches. The first branch contains a simple print statement, but the second branch contains another conditional statement, which has two branches of its own. Those two branches are both print statements, but they could have been conditional statements as well.

Indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. Avoid them when you can.

On the other hand, this kind of nested structure is common, and we will see it again, so you better get used to it.