Java Switch
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Syntax
switch(expression) < case x: // code block break; case y: // code block break; default: // code block >
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case .
- If there is a match, the associated block of code is executed.
- The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4; switch (day) < case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; >// Outputs "Thursday" (day 4)
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it’s time for a break. There is no need for more testing.
A break can save a lot of execution time because it «ignores» the execution of all the rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match:
Example
int day = 4; switch (day) < case 6: System.out.println("Today is Saturday"); break; case 7: System.out.println("Today is Sunday"); break; default: System.out.println("Looking forward to the Weekend"); >// Outputs "Looking forward to the Weekend"
Note that if the default statement is used as the last statement in a switch block, it does not need a break.
Can we use switch in java
Like all expressions, switch expressions evaluate to a single value and can be used in statements. They may contain » case L -> » labels that eliminate the need for break statements to prevent fall through. You can use a yield statement to specify the value of a switch expression.
For background information about the design of switch expressions, see JEP 361.
Consider the following switch statement that prints the number of letters of a day of the week:
public enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; >// . int numLetters = 0; Day day = Day.WEDNESDAY; switch (day) < case MONDAY: case FRIDAY: case SUNDAY: numLetters = 6; break; case TUESDAY: numLetters = 7; break; case THURSDAY: case SATURDAY: numLetters = 8; break; case WEDNESDAY: numLetters = 9; break; default: throw new IllegalStateException("Invalid day: " + day); >System.out.println(numLetters);
It would be better if you could «return» the length of the day’s name instead of storing it in the variable numLetters ; you can do this with a switch expression. Furthermore, it would be better if you didn’t need break statements to prevent fall through; they are laborious to write and easy to forget. You can do this with a new kind of case label. The following is a switch expression that uses the new kind of case label to print the number of letters of a day of the week:
Day day = Day.WEDNESDAY; System.out.println( switch (day) < case MONDAY, FRIDAY, SUNDAY ->6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException("Invalid day: " + day); > );
The new kind of case label has the following form:
case label_1, label_2, . label_n -> expression;|throw-statement;|block
When the Java runtime matches any of the labels to the left of the arrow, it runs the code to the right of the arrow and does not fall through; it does not run any other code in the switch expression (or statement). If the code to the right of the arrow is an expression, then the value of that expression is the value of the switch expression.
You can use the new kind of case label in switch statements. The following is like the first example, except it uses » case L -> » labels instead of » case L: » labels:
int numLetters = 0; Day day = Day.WEDNESDAY; switch (day) < case MONDAY, FRIDAY, SUNDAY ->numLetters = 6; case TUESDAY -> numLetters = 7; case THURSDAY, SATURDAY -> numLetters = 8; case WEDNESDAY -> numLetters = 9; default -> throw new IllegalStateException("Invalid day: " + day); >; System.out.println(numLetters);
A » case L -> » label along with its code to its right is called a switch labeled rule.
«case L:» Statements and the yield Statement
You can use » case L: » labels in switch expressions; a » case L: » label along with its code to the right is called a switch labeled statement group:
Day day = Day.WEDNESDAY; int numLetters = switch (day) < case MONDAY: case FRIDAY: case SUNDAY: System.out.println(6); yield 6; case TUESDAY: System.out.println(7); yield 7; case THURSDAY: case SATURDAY: System.out.println(8); yield 8; case WEDNESDAY: System.out.println(9); yield 9; default: throw new IllegalStateException("Invalid day: " + day); >; System.out.println(numLetters);
The previous example uses yield statements. They take one argument, which is the value that the case label produces in a switch expression.
The yield statement makes it easier for you to differentiate between switch statements and switch expressions. A switch statement, but not a switch expression, can be the target of a break statement. Conversely, a switch expression, but not a switch statement, can be the target of a yield statement.
It’s recommended that you use » case L -> » labels. It’s easy to forget to insert break or yield statements when using » case L: » labels; if you do, you might introduce unintentional fall through in your code.
For » case L -> » labels, to specify multiple statements or code that are not expressions or throw statements, enclose them in a block. Specify the value that the case label produces with the yield statement:
int numLetters = switch (day) < case MONDAY, FRIDAY, SUNDAY -> < System.out.println(6); yield 6; >case TUESDAY -> < System.out.println(7); yield 7; >case THURSDAY, SATURDAY -> < System.out.println(8); yield 8; >case WEDNESDAY -> < System.out.println(9); yield 9; >default -> < throw new IllegalStateException("Invalid day: " + day); >>;
Unlike switch statements, the cases of switch expressions must be exhaustive , which means that for all possible values, there must be a matching switch label. Thus, switch expressions normally require a default clause. However, for enum switch expressions that cover all known constants, the compiler inserts an implicit default clause.
In addition, a switch expression must either complete normally with a value or complete abruptly by throwing an exception. For example, the following code doesn’t compile because the switch labeled rule doesn’t contain a yield statement:
int i = switch (day) < case MONDAY -> < System.out.println("Monday"); // ERROR! Block doesn't contain a yield statement >default -> 1; >;
The following example doesn’t compile because the switch labeled statement group doesn’t contain a yield statement:
Because a switch expression must evaluate to a single value (or throw an exception), you can’t jump through a switch expression with a break , yield , return , or continue statement, like in the following example:
Java Switch Statement – How to Use a Switch Case in Java
Ihechikara Vincent Abba
You use the switch statement in Java to execute a particular code block when a certain condition is met.
Here’s what the syntax looks like:
Above, the expression in the switch parenthesis is compared to each case . When the expression is the same as the case , the corresponding code block in the case gets executed.
If all the cases do not match the expression , then the code block defined under the default keyword gets executed.
We use the break keyword to terminate the code whenever a certain condition is met (when the expression matches with a case ).
Let’s see some code examples.
How to Use a Switch Case in Java
Take a look at the following code:
In the code above, June is printed out. Don’t worry about the bulky code. Here’s a breakdown to help you understand:
We created an integer called month and assigned a value of 6 to it: int month = 6; .
Next, we created a switch statement and passed in the month variable as a parameter: switch (month) <. >.
The value of month , which is acting as the expression for the switch statement, will be compared with every case value in the code. We have case 1 to 12.
The value of month is 6 so it matches with case 6. This is why the code in case 6 was executed. Every other code block got ignored.
Here’s another example to simplify things:
In the example above, we created a string called username which has a value of «John».
In the switch statement, username is passed in as the expression. We then created three cases – «Doe», «John», and «Jane».
Out of the three classes, only one matches the value of username — «John». As a result, the code block in case «John» got executed.
How to Use the Default Keyword in a Switch Statement
In the examples in the previous section, our code got executed because one case matched an expression .
In this section, you’ll see how to use the default keyword. You can use it as a fallback in situations where none of the cases match the expression .
The username variable in the example above has a value of «Ihechikara».
The code block for the default keyword will be executed because none of the cases created match the value of username .
Summary
In this article, we saw how to use the switch statement in Java.
We also talked about the switch statement’s expression, cases, and default keyword in Java along with their use cases with code examples.