The if-else Statement 2 – Control Flow

Example 4.1 Fall-Through in a switch Statement with the Colon Notation

Click here to view code image

public class Advice {
  private static final int LITTLE_ADVICE = 0;
  private static final int MORE_ADVICE = 1;
  private static final int LOTS_OF_ADVICE = 2;
  public static void main(String[] args) {
    dispenseAdvice(LOTS_OF_ADVICE);
  }
  public static void dispenseAdvice(int howMuchAdvice) {
    switch (howMuchAdvice) {                                     // (1)
      case LOTS_OF_ADVICE: System.out.println(“See no evil.”);   // (2)
      case MORE_ADVICE:    System.out.println(“Speak no evil.”); // (3)
      case LITTLE_ADVICE:  System.out.println(“Hear no evil.”);  // (4)
                           break;                                // (5)
      default:             System.out.println(“No advice.”);     // (6)
    }
  }
}

Output from the program:

See no evil.
Speak no evil.
Hear no evil.

Several case labels can prefix the same group of statements. This is the equivalent of specifying the same case constants in a single case label. The latter syntax is preferable as it is more concise than the former. Such case constants will result in the associated group of statements being executed. This behavior is illustrated in Example 4.2 for the switch statement at (1).

At (2) in Example 4.2, three case labels are defined that are associated with the same action. At (3), (4), and (5), a list of case constants is defined for some of the case labels. Note also the use of the break statement to stop fall-through in the switch block after the statements associated with a case label are executed.

The first statement in the switch block must always have a case or default label; otherwise, it will be unreachable. This statement will never be executed because control can never be transferred to it. The compiler will flag this case (no pun intended) as an error. An empty switch block is perfectly legal, but not of much use.

Since each group of statements associated with a case label can be any arbitrary statement, it can also be another switch statement. In other words, switch statements can be nested. Since a switch statement defines its own local block, the case labels in an inner block do not conflict with any case labels in an outer block. Labels can be redefined in nested blocks; in contrast, variables cannot be redeclared in nested blocks (§6.6, p. 354). In Example 4.2, an inner switch statement is defined at (6), which allows further refinement of the action to take on the value of the selector expression in cases where multiple case labels are used in the outer switch statement. A break statement terminates the innermost switch statement in which it is executed.

The print statement at (7) is always executed for the case constants 9, 10, and 11.

Note that the break statement is the last statement in the group of statements associated with each case label. It is easy to think that the break statement is a part of the switch statement syntax, but technically it is not.

Example 4.2 Nested switch Statements with the Colon Notation

Click here to view code image

public class Seasons {
  public static void main(String[] args) {
    int monthNumber = 11;
    switch(monthNumber) {                                     // (1) Outer
      case 12: case 1: case 2:                                // (2)
        System.out.println(“Snow in the winter.”);
        break;
      case 3, 4: case 5:                                      // (3)
        System.out.println(“Green grass in the spring.”);
        break;
      case 6, 7, 8:                                           // (4)
        System.out.println(“Sunshine in the summer.”);
        break;
      case 9, 10, 11:                                         // (5)
        switch(monthNumber) { // Nested switch                   (6) Inner
          case 10:
            System.out.println(“Halloween.”);
            break;
          case 11:
            System.out.println(“Thanksgiving.”);
            break;
        } // End nested switch
        // Always printed for case constant 9, 10, 11
        System.out.println(“Yellow leaves in the fall.”);     // (7)
        break;
      default:
        System.out.println(monthNumber + ” is not a valid month.”);
    }
  }
}

Output from the program:

Click here to view code image

Thanksgiving.
Yellow leaves in the fall.

Passing Reference Values – Declarations

Passing Reference Values

If the actual parameter expression evaluates to a reference value, the resulting reference value on the stack is assigned to the corresponding formal parameter reference at method invocation. In particular, if an actual parameter is a reference to an object, the reference value stored in the actual parameter is passed. Consequently, both the actual parameter and the formal parameter are aliases to the object denoted by this reference value during the invocation of the method. In particular, this implies that changes made to the object via the formal parameter will be apparent after the call returns.

Type conversions between actual and formal parameters of reference types are discussed in §5.10, p. 265.

In Example 3.11, a Pizza object is created at (1). Any object of the class Pizza created using the class declaration at (5) always results in a beef pizza. In the call to the bake() method at (2), the reference value of the object referenced by the actual parameter favoritePizza is assigned to the formal parameter pizzaToBeBaked in the declaration of the bake() method at (3).

Example 3.11 Passing Reference Values

Click here to view code image

public class CustomerTwo {
  public static void main (String[] args) {
    Pizza favoritePizza = new Pizza();              // (1)
    System.out.println(“Meat on pizza before baking: ” + favoritePizza.meat);
    bake(favoritePizza);                            // (2)
    System.out.println(“Meat on pizza after baking: ” + favoritePizza.meat);
  }
  public static void bake(Pizza pizzaToBeBaked) {   // (3)
    pizzaToBeBaked.meat = “chicken”;  // Change the meat on the pizza.
    pizzaToBeBaked = null;                          // (4)
  }
}

class Pizza {                                       // (5)
  String meat = “beef”;
}

Output from the program:

Click here to view code image

Meat on pizza before baking: beef
Meat on pizza after baking: chicken

One particular consequence of passing reference values to formal parameters is that any changes made to the object via formal parameters will be reflected back in the calling method when the call returns. In this case, the reference favoritePizza will show that chicken has been substituted for beef on the pizza. Setting the formal parameter pizzaToBeBaked to null at (4) does not change the reference value in the actual parameter favoritePizza. The situation at method invocation, and just before the return from method bake(), is illustrated in Figure 3.3.

Figure 3.3 Parameter Passing: Reference Values

In summary, the formal parameter can only change the state of the object whose reference value was passed to the method.

The parameter passing strategy in Java is call by value and not call by reference, regardless of the type of the parameter. Call by reference would have allowed values in the actual parameters to be changed via formal parameters; that is, the value in pricePrPizza would be halved in Example 3.10 and favoritePizza would be set to null in Example 3.11. However, this cannot be directly implemented in Java.