Java

Java Switch and Nested Switch Statements

  • Java
  • 7 mins read

The switch statement is Java’s multiway branch statement. It offers the simplest way to dispatch execution to other parts of your code based on the value of an expression. Essentially, it often provides a better alternative than a long series of if-else-if statements. Here is the usual form of a switch statement:

Java Switch Statement

switch (expression) 
{ case value1:

// statement sequence

break; 
case value2:

// statement sequence

break;
 .
 .
 .
case valueN :
// statement sequence 
break;
default:
// default statement sequenc

For versions of Java before JDK 7, the expression must be of type byte, short, int, char, or an enumeration. Starting with JDK 7, an expression can also be of type String. Each value particularized in the case statements must be a different constant expression such as a literal value. The kind of each value must be compatible with the type of expression.

The switch statement operates like this: The value of the expression is matched with each of the values in the case statements. If a match is detected, the code sequence following that case statement is performed(executed). If none of the constants pairs the value of the expression, then the default statement is executed. Nevertheless, the default statement is optional and not compulsory. If no case matches or pairs and no default is present, then no more action is taken.

The break statement is applied inside the switch to end a statement sequence. When a break statement is found, execution branches to the first line of code that follows the complete switch statement, this has the impact of “jumping out” of the switch.

Here is a simplistic example that uses a switch statement:

// A simple example of the switch.
class SampleSwitch {
  public static void main(String args[]) {
    for(int i=0; i<6; i++)
      switch(i) {
        case 0:
          System.out.println("i is zero.");
          break;
        case 1:
          System.out.println("i is one.");
          break;
        case 2:
          System.out.println("i is two.");
          break;
        case 3:
          System.out.println("i is three.");
          break;
        default:
          System.out.println("i is greater than 3.");
      }
  } 
}

The result produced by this program is shown here:

    i is zero.
    i is one.
    i is two.
    i is three.
    i is greater than 3.
    i is greater than 3.

As you can notice, each time within the loop, the statements correlated with the case constant that matchesi are executed. All others are avoided. After i is greater than 3, no case statements pair, so the default statement is executed.

The break statement is optional and not compulsory. If you neglect the break, execution will proceed into the next case. It is seldom advisable to have multiple cases without break statements between them. For example, consider the following program:

// In a switch, break statements are optional.
class MissingBreak {
  public static void main(String args[]) {
    for(int i=0; i<12; i++)
      switch(i) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
          System.out.println("i is less than 5");
          break;
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          System.out.println("i is less than 10");
          break;
        default:
          System.out.println("i is 10 or more");
      }
   }
}

This program produces the following output:

    i is less than 5
    i is less than 5
    i is less than 5
    i is less than 5
    i is less than 5
    i is less than 10
    i is less than 10
    i is less than 10
    i is less than 10
    i is less than 10
    i is 10 or more
    i is 10 or more

As you can see, execution occurs through each case until a break statement (or the end of the switch) is approached.

While the prior example is, of course, made for the sake of illustration, eliminating the break statement has many practical applications in actual programs. To test its more effective usage, consider the following rewrite of the season example given earlier. This version uses a switch to render a more efficient implementation.

// An improved version of the season program. class Switch { public static void main(String args[]) {
int month = 4;
String season;
    switch (month) {
      case 12:
      case 1:
      case 2:
        season = "Winter";
        break;
      case 3:
      case 4:
      case 5:
        season = "Spring";
        break;
      case 6:
      case 7:
      case 8:
        season = "Summer";
        break;
      case 9:
      case 10:
      case 11:
        season = "Autumn";
        break;
      default:
        season = "Bogus Month";
    }
    System.out.println("April is in the " + season + ".");
  }


}

As discussed, beginning with JDK 7, you can make use of a string to control a switch statement. For example,

// Use a string to control a switch statement.
class StringSwitch {
  public static void main(String args[]) {
    String str = "two";
    switch(str) {
      case "one":
        System.out.println("one");
        break;
      case "two":
        System.out.println("two");
        break;
      case "three":
        System.out.println("three");
        break;
      default:
        System.out.println("no match");
        break; 
      }
   } 
}

As you would expect, the result of the program is

two

The string enclosed in str (which is "two" in this program) is examined against the case constants. When a match is detected, the code sequence associated with that sequence is executed.

Being able to use strings in a switch statement streamlines numerous situations. For instance, using a string-based switch is an advancement over using the equivalent sequence of if/else statements. Nevertheless, switching on strings can be more expensive than switching on integers. Hence, it is sufficient to switch on strings, particularly in cases in which the controlling data is already in string form. In other words, don’t use strings in a switch unnecessarily.

Nested switch Statements

You can make use of a switch as part of the statement sequence of an outer switch. This is termed as a nested switch. Since a switch statement clarifies its block, no disputes occur between the case constants in the inner switch and those in the outer switch. For instance, the following fragment is quite valid:

switch(count) {
  case 1:
    switch(target) { // nested switch
      case 0:
        System.out.println("target is zero");
        break;
      case 1: // no conflicts with outer switch
        System.out.println("target is one");
       break;
}
break;
case 2: // ...

Here, case 1: statement in the inner switch does not clash with the case 1: statement in the outer switch. The count variable is matched only with the list of cases at the external level. If the count is 1, then the target is paired with the inner list cases.

In summary, there are three major features of the switch statement to note:

  • The switch varies from the if in that switch can only test for equality, whereas if can evaluate any Boolean expression. That is, the switch looks only for a match within the value of the expression and one of its case constants.
  • No two case constants in the same switch can have similar values. Of course, a switch statement and an enclosing outer switch can hold case constants in common.
  • A switch statement usually is more effective than a set of nested ifs.

The last point is especially interesting because it gives insight into how the Java compiler works. When it compiles a switch statement, the Java compiler will examine each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression.

Hence, if you need to pick among a broad group of values, a switch statement will run much quicker than the comparable logic coded using a sequence of if-elses. The compiler can do this because it recognizes that the case constants are all the same type and must be compared for equality with the switch expression. The compiler has no such information of a long list of if expressions.

See also: