The switch Statement

In this lesson, we will introduce the Java switch statement that provides a clear way to define a multiway decision.

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:

Press + to interact
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. ...

Access this course and 1400+ top-rated courses and projects.