The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


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. Fortunately, those two branches are both print statements, although they could have been conditional statements as well.

Notice again that indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. In general, it is a good idea to 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.



Last Update: 2011-01-24