Chained conditionals

Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses:

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

These chains can be as long as you want, although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all the statements and squiggly-brackets lined up, you are less likely to make syntax errors and more likely to find them if you do.