Java switch Statement
The switch statement in Java is used when we need to test a variable against multiple possible values. It is an alternative to using multiple if-else-if statements and makes the code more readable and efficient.
In this blog, we will cover:
- What is the
switchstatement? - How does the
switchstatement work? - Syntax of
switch - Example programs with explanations
- Rules and limitations of
switch - Enhanced
switchstatement in Java 12+
What is the switch Statement?#
A switch statement allows a variable to be tested against multiple values, executing different blocks of code depending on which value matches.
Instead of writing multiple if-else-if conditions, we can use switch for better readability.
How Does the switch Statement Work?#
- The
switchstatement evaluates an expression. - The result of the expression is compared with multiple case values.
- If a match is found, the corresponding block of code executes.
- The
breakstatement stops execution after a case is matched. - If no cases match, the
defaultcase (if provided) is executed.
Syntax of switch Statement#
Example 1: Basic switch Statement#
Expected Output#
Explanation:
- The variable
dayis3, so it matchescase 3:. "Wednesday"is printed.- The
breakstatement exits theswitchblock.
Example 2: switch with char#
Expected Output#
Explanation:
- The variable
gradeis'B', so it matchescase 'B':. "Good job!"is printed.
Example 3: switch without break#
If we do not use the break statement, execution will continue to the next case.
Expected Output#
Explanation:
- The value
2matchescase 2:. - Since there's no
break, execution continues to the next cases.
Example 4: switch with Strings (Java 7+)#
Java allows switch statements with String values starting from Java 7.
Expected Output#
Example 5: Nested switch Statement#
We can use one switch inside another switch.
Expected Output#
Enhanced switch in Java 12+#
From Java 12 onwards, switch is enhanced with a new syntax.
Example 6: Enhanced switch with >#
Expected Output#
Explanation:
- The
switchreturns a value directly. - We use
>instead of:to make the code cleaner.
Rules and Limitations of switch#
- Expression type:
switchworks withbyte,short,char,int,String, andenum. - No
long,float,double, or boolean values allowed. - Duplicate case values are not allowed.
- Use
breakto prevent fall-through. defaultis optional but recommended.
Conclusion#
In this blog, we have learned:
- The
switchstatement is an alternative to multipleif-else-ifconditions. - It compares a variable against multiple case values.
- The
breakstatement prevents execution from falling through to the next case. - The
defaultcase executes when no other case matches. switchsupports String (Java 7+) and has an enhanced form (Java 12+).
Using switch makes your code cleaner and more readable, especially when checking a single variable against multiple possible values.