Search⌘ K

The switch Statement

Explore how to use the Java switch statement for efficient decision-making based on expression values such as integers, characters, strings, or enums. Learn to write clear multiway decision code, use case labels, and apply default cases effectively, helping you create cleaner and more readable Java programs.

What is a switch statement?

We can use a switch statement when a decision depends on the value of an expression. This value’s data type must be either

  • char
  • An integer type such as int
  • An enumeration, or
  • A string

Example 1

For example, if the int variable dayNumber has a value ranging from 1 to 7 to indicate one of the days Sunday through Saturday, we need not use an if-else statement to produce the day of the week as a string. Instead, we can use the following switch statement:

Java
public class Example1
{
public static void main(String args[])
{
// Assume that dayNumber contains an integer that ranges from 1 to 7.
int dayNumber = 5; // Fee free to change this value.
String dayName = null;
switch (dayNumber)
{
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "ERROR";
assert false: "Error in dayNumber: " + dayNumber;
break;
} // End switch
System.out.println("Day " + dayNumber + " is a " + dayName);
} // End main
} // End Example1

In this example, dayNumber is the expression that is tested. We must be able to list the values of the expression to be able to use a switch statement. Such is the situation here since dayNumber has one of the values 1 through 7. Each value of the tested expression corresponds to a case within the switch statement. When the value of the expression matches the value in a case—called the case ...