The switch Statement
In this lesson, we will introduce the Java switch statement that provides a clear way to define a multiway decision.
We'll cover the following...
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:
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 ...