Java Switch Statement (Beginner Friendly + Practical Examples)
β What is a Switch Statement?
The switch
statement in Java is a type of control flow statement used to execute one block of code out of many based on the value of a given expression. It’s commonly used as a cleaner alternative to multiple if-else-if
statements when you are comparing the same variable with different constant values.
Using switch
improves code readability and reduces complexity when you need to make a decision among several fixed options.
π§ Syntax of Switch Statement
π Key Points:
-
The
expression
must be of typebyte
,short
,int
,char
,String
, orenum
. -
Each
case
is followed by a colon:
and a block of code to execute. -
The
break
keyword stops the execution from continuing to the next case. -
If
break
is not used, Java performs fall-through to the next case. -
The
default
block is optional and is executed when no other case matches.
π― Example 1: Simple Switch with Integers
Output:
π― Example 2: Switch with String
Output:
β οΈ Fall-Through Behavior
If you forget to use break
, Java will continue to execute all the following cases, even if they donβt match.
Output:
Explanation:
Since there is no break
after case 2, Java continues to execute case 3 as well. This is called fall-through, and it’s something to be cautious about.
β When to Use Switch
-
When comparing a single variable against several constant values.
-
When you want cleaner code than multiple
if-else-if
blocks. -
When readability and structure matter, especially for large sets of conditions.
-
When working with fixed values like menu choices, days of the week, or status codes.