switch statements

 

Overview

Flow control with if and else statements gets cumbersome when a variable must be tested for a large number of possible values, such as a menu selection that permits the user to enter an integer from 1 to 20. The solution to this problem is the switch statement.

 

The switch statement

switch (expression) {
 
case value1: 
   
statements
; 
    break; 
  case value2: 
   
statements
; 
    break; 
  default:
   
statements
; 
    break; 
}

  1. The switch expression must be a primitive of type int or able to be promoted to int. Specifically, it must be either byte, short, int, or char. Expressions of type boolean, long, float, and double will not compile.

  2. The value specified on a case must be a constant of type int or must be able to be promoted to int (in other words a byte, short, int, or char). It must also be within the possible range of values of the switch expression. For example, if the switch variable is a byte, a case with a value of 200 would not compile because a byte may only have a value from -128 to 127.

The value of a case may be an expression as long as the result is a constant. For example,

case 5 + 1:

would compile successfully.

  1. The break statement is optional and will be covered in more detail in a later lesson. When encountered, it ends the execution of the switch statement. If omitted from a case, processing falls through to the next case (a sometimes undesirable result).

  2. Although the compiler doesn't care, cases should be arranged in a high probability to low probability order to enhance processing efficiency. The default can be placed anywhere (even first).

 

Example

The following program is a revised version of the nested if-else sample from the previous lesson:

public class App {
  public static void main(String[] args) {

    // Variables

    double balance;
    char code;
    double amount;

    // Prompt for and read data

    System.out.print("Enter customer's starting balance: ");
    balance = Keyboard.readDouble();
    System.out.print("Enter transaction amount: ");
    amount = Keyboard.readDouble();
    System.out.println("Transaction codes are");
    System.out.println("\t" + "C - charge");
    System.out.println("\t" + "P - payment");
    System.out.println("\t" + "R - refund or return");
    System.out.print("Enter transaction code: ");
    code = Keyboard.readChar();

    // Process based upon transaction code

    switch (code) {
      case 'C':
      case 'c':
        balance += amount;
        System.out.println("New balance is " + Utility.moneyFormat(balance));
        break;
      case 'P':
      case 'p':
        balance -= amount;
        System.out.println("New balance is " + Utility.moneyFormat(balance));
        break;
      case 'R':
      case 'r':
        balance -= amount;
        System.out.println("New balance is " + Utility.moneyFormat(balance));
        break;
      default:
        System.out.println("Invalid transaction code");
        break;
    }
  }
}

Notes: 

  1. The balance, code, and amount variables hold data entered by the user.

  2. After all data has been read from the user, the transaction is processed by the switch statement with the transaction code (code) used as the switch expression.

  3. Within the switch, if the value of code matches the value of a particular case, processing jumps to the statement block for that case, otherwise processing jumps to the statement block for the default. Processing will then continue until either a break statement is encountered or the end of the switch is reached.

  4. Stacking two or more cases without at break statement constitutes an OR. For example,

case 'R':
case 'r':

will result in the same processing being performed if the value of code is either an uppercase or lowercase 'R'.

  1. For transactions with a valid transaction code, the customer's new balance is displayed using the moneyFormat() method of my Utility class. If the transaction code is bad, an error message is displayed.

 

Review questions

  1. Assuming that all unseen code is correct and that line numbers are for reference purposes only, what will result from an attempt to compile and execute the following statements?

1
2
3
4
5
6
7
8
9

int j = 5;
switch (j + 2) {
  case 5:
    System.out.println("Value is 5");
  case 6 + 1:
    System.out.println("Value is 7");
  default:
    System.out.println("Some other value");
}

  1. a compile error will occur at line 2

  2. a compile error will occur at line 5

  3. Value is 5

  4. Value is 7

  5. Value is 7
    Some other value

  1. Assuming that all unseen code is correct and that line numbers are for reference purposes only, what will result from an attempt to compile and execute the following statements?

1
2
3
4
5
6
7
8
9
10
11

double x = 5.0;
switch (x) {
  case 5:
    System.out.println("Value is 5");
    break;
  case 7:
    System.out.println("Value is 7");
    break;
  default:
    System.out.println("Some other value");
}

  1. a compile error will occur at line 1

  2. a compile error will occur at line 2

  3. the statements will compile successfully but a runtime error will occur at line 2

  4. Value is 5

  5. Some other value

  1. If the type of a switch expression is char, which of the following case statements are valid?  (choose four)

  1. case 'x':

  2. case 'x' + 2:

  3. case 'x' - 3:

  4. case -3:

  5. case 128:

  1. Which of the following are invalid types for a switch expression?  (choose four)

  1. boolean

  2. long

  3. short

  4. float

  5. double