Last Updated: 28 May, 2022
In Java, the switch statement allows us to execute a block of statements among many alternatives options. It is similar to the Java if...else...if ladder.
The expression can be a byte, short, char, or int (primitive data types). Since Java 7, it also works with enumerated types (Enums in java), the String class, and Wrapper classes.
Syntax for writing switch statement in Java
Flowchart of Switch Statement
Some Important points for switch statements
Coding Tips: If the number of cases exceeds 5, always use switch statement in your programming, otherwise if-else can be used.
Example 1 : Switch Statement implementation in Java
Output
It is Tuesday
Example 2 : Switch Statement implementation using String
Using strings in a switch expression is possible since Java SE 7. The case statement must be a string literal. Let's see the below given example.
Output
Master of Computer Application
Example 3 : Switch Statement implementation using Enums
Output
Your colour is Green.
Example 4 : Switch Statement without break Keyword using Wrapper Class
Output
It's a Working Day
Example 5 : Nested Switch Statements implementation in Java
Java allows to write nested switch statements that means one switch statement can contain another switch statement just like nested if-else statement. Let's see the program and try to understand how to implement nested switch statements.
Output
Nursery - 'B', Total Students: 38
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What type of expression a switch statement contains?
Ans. Switch expressions must be of the following types:
Why break statement is used inside the switch?
The break statement is mainly used to terminate a statement sequence and jumps the control after the switch expression. 'break' keyword is optional, if we skip the break statement execution will continue on into the next case.