3. Chained & Nested If Statements

3.1. Objectives

  • Identify and use the if statement in chaining and nesting in Java

3.2. Time Goal

  • 20 minutes on this section

3.3. Key Terms

chaining
A way of joining several conditional statements in sequence.
nesting
Putting a conditional statement inside one or both branches of another conditional statement.

3.4. Exercises

Note

Sometimes you want to check related conditions and choose one of several actions. One way to do this is by chaining a series of if and else blocks:

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 braces lined up, you are less likely to make syntax errors.

Notice that the last branch is simply else, not else if (x == 0). At this point in the chain, we know that x is not positive and x is not negative. There is no need to test whether x is zero, because there is no other possibility.

In addition to chaining, you can also make complex decisions by nesting one conditional statement inside another. We could have written the previous example as:

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");
   }
}

The outer conditional has two branches. The first branch contains a print statement, and the second branch contains another conditional statement, which has two branches of its own. These two branches are also print statements, but they could have been conditional statements as well.

These kinds of nested structures are common, but they can become difficult to read very quickly. Good indentation is essential to make the structure (or intended structure) apparent to the reader.

You can even pick between 3 or more possibilites. Just add else if for each possibility after the first if, but instead add else before the last possibility.

../../_images/Condition-three.png

Figure 1: The order that statements execute in a conditional with 3 options: if, else if, and else

Run the code below and try changing the value of x to get each of the three possible lines in the conditional to print.

Note

Another way to handle 3 or more conditional cases is to use the switch and break keywords, but these will not be on the exam. For a tutorial on using switch see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html.

Check your understanding

    Q-24: What does the following code print when x has been set to -5?

    if (x < 0)
        System.out.println("x is negative");
    else if (x == 0) System.out.println("x is zero");
    else {
        System.out.println("x is positive");
    }
    
  • x is negative
  • When x is equal to -5 the condition of x < 0 is true.
  • x is zero
  • This will only print if x has been set to 0. Has it?
  • x is positive
  • This will only print if x is greater than zero. Is it?

    Q-25: What does the following code print when x has been set to 2000?

    if (x < 0)
        System.out.println("x is negative");
    else if (x == 0)
        System.out.println("x is zero");
    else
        System.out.println("x is positive");
    
  • x is negative
  • This will only print if x has been set to a number less than zero. Has it?
  • x is zero
  • This will only print if x has been set to 0. Has it?
  • x is positive
  • The first condition is false and x is not equal to zero so the else will execute.

    Q-26: What does the following code print when x has been set to .8?

    if (x < .25)
        System.out.println("first quartile");
    else if (x < .5)
        System.out.println("second quartile");
    else if (x < .75)
        System.out.println("third quartile");
    else
        System.out.println("fourth quartile");
    
  • first quartile
  • This will only print if x is less than 0.25.
  • second quartile
  • This will only print if x is greater than or equal to 0.25 and less than 0.5.
  • third quartile
  • The first only print if x is greater than or equal to 0.5 and less than 0.75.
  • fourth quartile
  • This will print whenever x is greater than 0.75.
        Q-28: Q-27: The main method in the following class should print out if a string has the word "cake" in it or not.
But, the blocks have been mixed up and includes an extra block that isn't needed in the solution.  Drag the needed blocks from the left and put them in the correct order on the right.  Click the Check Me button to check your solution.
(You may want to refer to the API documentation for String to see what one of the methods does: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html )

public class Test1 { --- public static void main(String[] args) { --- String message = "Order the cake today"; --- if (message.indexOf(" cake ") >= 0) --- if (message.indexof(" cake ") >= 0) #paired --- System.out.println("Message mentions cake"); --- else --- System.out.println("No mention of cake"); --- } }
        Q-30: Q-29: The main method in the following class should print your grade for score. But, the blocks have been mixed up.  Drag the needed blocks from the left and put them in the correct order on the right.  Click the Check Me button to check your solution.

public class Test1 { public static void main(String[] args) { --- int score = 73; --- if (score >= 90) --- System.out.println("A"); --- else if (score >= 80) --- System.out.println("B"); --- else if (score >= 70) System.out.println("C"); --- else if (score >= 60) System.out.println("D"); --- else System.out.println("E"); --- } }
Next Section - 4. Logical Operators