Java switch statement will allow you to check for a number of conditions to execute the statements. It works like an if-else-if statement. The switch statement will allow you to use byte, short, int, long, enum types, String, and some wrapper types like Byte, Short, Int, and Long.
With the latest version of Java, you can also use strings in the switch statement. There is no limitation on the number of cases you will use within a single switch statement. The case value must match the types of the switch expression, which can be constant or literal.
You cannot use a variable for the case value. All case values must be different from each other else you will get a compile-time error. You can use an optional break statement in each case statement. If you do not use the break statement , then the control will go to the next case statement else. The control will be out of the switch expression.
Syntax
Example
Output
Example Without Break Statement
If there is no break statement encountered then the matched case statement will get executed and the case statements after that.
Output
In the above example, the case with value 20 and the case statement after that will get executed.
Example Using a String as the Switch Expression
Output
Nested Switch Example
Output
Switch Example with enum
Output
Wrapper in a Switch Statement
It allows you to use wrapper classes like byte, short, integer, and long as the switch expression.
Output
Conclusion
Java switch-case is a multi-way branch statement analogous to the if-else-if ladder. It allows you to specify multiple conditions or cases as you wish. In this tutorial, we have provided various examples to help you gain clarity on the switch-case statement in Java. Refer to those examples and try them yourself.
Good Luck!
People are also reading: