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.
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 ...