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
switch
statement? - How does the
switch
statement work? - Syntax of
switch
- Example programs with explanations
- Rules and limitations of
switch
- Enhanced
switch
statement 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
switch
statement 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
break
statement stops execution after a case is matched. - If no cases match, the
default
case (if provided) is executed.
Syntax of switch
Statement#
Example 1: Basic switch
Statement#
Expected Output#
Explanation:
- The variable
day
is3
, so it matchescase 3:
. "Wednesday"
is printed.- The
break
statement exits theswitch
block.
Example 2: switch
with char
#
Expected Output#
Explanation:
- The variable
grade
is'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
2
matchescase 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
switch
returns a value directly. - We use
>
instead of:
to make the code cleaner.
Rules and Limitations of switch
#
- Expression type:
switch
works withbyte
,short
,char
,int
,String
, andenum
. - No
long
,float
,double
, or boolean values allowed. - Duplicate case values are not allowed.
- Use
break
to prevent fall-through. default
is optional but recommended.
Conclusion#
In this blog, we have learned:
- The
switch
statement is an alternative to multipleif-else-if
conditions. - It compares a variable against multiple case values.
- The
break
statement prevents execution from falling through to the next case. - The
default
case executes when no other case matches. switch
supports 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.