The switch Statement

Basics

The switch Statement

🙋 Need help? Ask an expert now!

The switch statement compares different primitive data types, String values and other objects to tests whether or not they are equal to a certain value. Play with the example of a switch statement below by changing the value of exampleVariableOne to see the different results.

SwitchStatementExample.java
package exlcode;

public class SwitchStatementExample {

  public static int exampleVariableOne = 37;

  public static void main(String[] args) {
    // checks to see which number exampleVariableOne is
    // between 35-40
    switch (exampleVariableOne /* expression */){
      case 35: // 35 is a label
        System.out.println("exampleVariableOne is 35");
        break;
      case 36: // 36 is a label
        System.out.println("exampleVariableOne is 36");
        break;
      case 37: // 37 is a label
        System.out.println("exampleVariableOne is 37");
        break;
      case 38:
        System.out.println("exampleVariableOne is 38");
        break;
      case 39:
        System.out.println("exampleVariableOne is 39");
        break;
      case 40:
        System.out.println("exampleVariableOne is 40");
        break;
      default:
        System.out.println("exampleVariableOne has to be between 35 and 40");
    }
  }
}

The switch statement tests to see whether or not exampleVariableOne is between 35 and 40. Each "case" within the switch statement checks to see if exampleVariableOne is a certain number, and prints different statements depending on the value exampleVariableOne holds. Keep in mind, just one of these cases is selected per execution of the switch statement, and the data type of the expression has to match the datatype of the label. If none of the case labels matches the value of the expression, the default case is used, and its statements are executed.

A programmer can write many statements after each case, usually followed by a break statement which stops anything after the case from being executed. Let's return to the example above and remove the break statement to see the result and the importance of having a break statement.

Application Question

What is the value of varTwo after the following switch statement is executed?

int varOne = 3;
int varTwo = 4;
switch (varOne+3){
  case 6:
    varTwo = 0;
  case 7:
    varTwo = 1;
  default:
    varTwo += 1;
}