Java Switch Statements:
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed.Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
Syntax:
switch(expression)
{
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
....
....
....
default :
// default Statement
}
Example: Size Printer Example
1
public class SizePrinter {
2
3
public static void main(String[] args) {
4
int sizeNumber = 2; // Replace with your desired size (1, 2, 3, 4, or 5)
5
6
switch (sizeNumber) {
7
case 1:
8
System.out.println("Extra Small");
9
break;
10
case 2:
11
System.out.println("Small");
12
break;
13
case 3:
14
System.out.println("Medium");
15
break;
16
case 4:
17
System.out.println("Large");
18
break;
19
case 5:
20
System.out.println("Extra Large");
21
break;
22
default:
23
System.out.println("Invalid size number");
24
}
25
}
26
}
Output
Small
Some Important Rules for Java Switch Statements
Case values must be constants or literals and of the same type as the switch expression.
Duplicate case values are not allowed.
The break statement is used to exit from the switch block. It is optional but recommended to prevent fall-through.
The default case is optional and executes if no case matches the switch expression. It can appear anywhere within the switch block.
Note: Starting from Java 7, switch statements can use String type values. They can also handle wrapper classes like Integer, Short, Byte, Long.
Flowchart of Switch-Case Statement
This flowchart shows the control flow and working of switch statements:
switch statement flowchart in java
Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case.
Example: Finding Day
Consider the following Java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement.
1
// Java program to Demonstrate Switch Case
2
// with Primitive(int) Data Type
3
4
// Class
5
public class GFG {
6
7
// Main driver method
8
public static void main(String[] args)
9
{
10
int day = 5;
11
String dayString;
12
13
// Switch statement with int data type
14
switch (day) {
15
16
// Case
17
case 1:
18
dayString = "Monday";
19
break;
20
21
// Case
22
case 2:
23
dayString = "Tuesday";
24
break;
25
26
// Case
27
case 3:
28
dayString = "Wednesday";
29
break;
30
31
// Case
32
case 4:
33
dayString = "Thursday";
34
break;
35
36
// Case
37
case 5:
38
dayString = "Friday";
39
break;
40
41
// Case
42
case 6:
43
dayString = "Saturday";
44
break;
45
46
// Case
47
case 7:
48
dayString = "Sunday";
49
break;
50
51
// Default case
52
default:
53
dayString = "Invalid day";
54
}
55
System.out.println(dayString);
56
}
57
}
Output
Friday
Break in switch case Statements
A break statement is optional. If we omit the break, execution will continue into the next case.
It is sometimes desirable to have multiple cases without “break” statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day.
Example: Switch statement program without multiple breaks
1
// Java Program to Demonstrate Switch Case
2
// with Multiple Cases Without Break Statements
3
4
// Class
5
public class GFG {
6
7
// main driver method
8
public static void main(String[] args)
9
{
10
int day = 2;
11
String dayType;
12
String dayString;
13
14
// Switch case
15
switch (day) {
16
17
// Case
18
case 1:
19
dayString = "Monday";
20
break;
21
22
// Case
23
case 2:
24
dayString = "Tuesday";
25
break;
26
27
// Case
28
case 3:
29
dayString = "Wednesday";
30
break;
31
case 4:
32
dayString = "Thursday";
33
break;
34
case 5:
35
dayString = "Friday";
36
break;
37
case 6:
38
dayString = "Saturday";
39
break;
40
case 7:
41
dayString = "Sunday";
42
break;
43
default:
44
dayString = "Invalid day";
45
}
46
47
switch (day) {
48
// Multiple cases without break statements
49
50
case 1:
51
case 2:
52
case 3:
53
case 4:
54
case 5:
55
dayType = "Weekday";
56
break;
57
case 6:
58
case 7:
59
dayType = "Weekend";
60
break;
61
62
default:
63
dayType = "Invalid daytype";
64
}
65
66
System.out.println(dayString + " is a " + dayType);
67
}
68
}
Output
Tuesday is a Weekday
Java Nested Switch Statements
We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its block, no conflicts arise between the case constants in the inner switch and those in the outer switch.
Example: Nested Switch Statement
1
// Java Program to Demonstrate
2
// Nested Switch Case Statement
3
4
// Class
5
public class GFG {
6
7
// Main driver method
8
public static void main(String[] args)
9
{
10
// Custom input string
11
String Branch = "CSE";
12
int year = 2;
13
14
// Switch case
15
switch (year) {
16
17
// Case
18
case 1:
19
System.out.println(
20
"elective courses : Advance english, Algebra");
21
22
// Break statement to hault execution here
23
// itself if case is matched
24
break;
25
26
// Case
27
case 2:
28
29
// Switch inside a switch
30
// Nested Switch
31
switch (Branch) {
32
33
// Nested case
34
case "CSE":
35
case "CCE":
36
System.out.println(
37
"elective courses : Machine Learning, Big Data");
38
break;
39
40
// Case
41
case "ECE":
42
System.out.println(
43
"elective courses : Antenna Engineering");
44
break;
45
46
// default case
47
// It will execute if above cases does not
48
// execute
49
default:
50
51
// Print statement
52
System.out.println(
53
"Elective courses : Optimization");
54
}
55
}
56
}
57
}
Output
elective courses : Machine Learning, Big Data
Java Enum in Switch Statement
Enums in Java are a powerful feature used to represent a fixed set of constants. They can be used in switch statements for better type safety and readability.
Example: Use of Enum in Switch
1
// Java Program to Illustrate Use of Enum
2
// in Switch Statement
3
4
// Class
5
public class GFG {
6
7
// Enum
8
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
9
10
// Main driver method
11
public static void main(String args[])
12
{
13
14
// Enum
15
Day[] DayNow = Day.values();
16
17
// Iterating using for each loop
18
for (Day Now : DayNow) {
19
20
// Switch case
21
switch (Now) {
22
23
// Case 1
24
case Sun:
25
System.out.println("Sunday");
26
27
// break statement that hault further
28
// execution once case is satisfied
29
break;
30
31
// Case 2
32
case Mon:
33
System.out.println("Monday");
34
break;
35
36
// Case 3
37
case Tue:
38
System.out.println("Tuesday");
39
break;
40
41
// Case 4
42
case Wed:
43
System.out.println("Wednesday");
44
break;
45
46
// Case 5
47
case Thu:
48
System.out.println("Thursday");
49
break;
50
51
// Case 6
52
case Fri:
53
System.out.println("Friday");
54
break;
55
56
// Case 7
57
case Sat:
58
System.out.println("Saturday");
59
}
60
}
61
}
62
}
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Default statement in Java Switch Case
The default case in a switch statement specifies the code to run if no other case matches. It can be placed at any position in the switch block but is commonly placed at the end.
Example: Writing default in the middle of switch statements:
1
import java.io.*;
2
3
class GFG {
4
public static void main (String[] args) {
5
int i=2;
6
switch(i){
7
default:
8
System.out.println("Default");
9
case 1:
10
System.out.println(1);
11
break;
12
case 2:
13
System.out.println(2);
14
case 3:
15
System.out.println(3);
16
17
}
18
}
19
}
Output
2
3
Example: Writing Default at the Beginning of Switch Statements
1
import java.io.*;
2
3
class GFG {
4
public static void main(String[] args)
5
{
6
int i = 5;
7
switch (i) {
8
default:
9
System.out.println("Default");
10
case 1:
11
System.out.println(1);
12
break;
13
case 2:
14
System.out.println(2);
15
case 3:
16
System.out.println(3);
17
}
18
}
19
}
Output
Default
1
Case label variations
Case labels and switch arguments can be constant expressions. The switch argument can be a variable expression but the case labels must be constant expressions.
Example: Using Variable in Switch Argument
1
import java.io.*;
2
3
class GFG {
4
public static void main(String[] args)
5
{
6
int x = 2;
7
switch (x + 1) {
8
case 1:
9
System.out.println(1);
10
break;
11
case 1 + 1:
12
System.out.println(2);
13
break;
14
case 2 + 1:
15
System.out.println(3);
16
break;
17
default:
18
System.out.println("Default");
19
}
20
}
21
}
Output
3
Example: Case Label Cannot Be Variable
A case label cannot be a variable or variable expression. It must be a constant expression.
1
import java.io.*;
2
3
class GFG {
4
public static void main(String[] args)
5
{
6
int x = 2;
7
int y = 1;
8
switch (x) {
9
case 1:
10
System.out.println(1);
11
break;
12
case 2:
13
System.out.println(2);
14
break;
15
case x + y:
16
System.out.println(3);
17
break;
18
default:
19
System.out.println("Default");
20
}
21
}
22
}
./GFG.java:16: error: constant expression required
case x+y:
^
1 error
Java Wrapper in Switch Statements
Java allows the use of wrapper classes (Integer, Short, Byte, Long, and Character) in switch statements. This provides flexibility when dealing with primitive data types and their corresponding wrapper types.
Example: Using Wrapper Classes
1
public class WrapperSwitchExample {
2
3
public static void main(String[] args) {
4
Integer age = 25;
5
6
switch (age) { // Extract primitive value for switch
7
case 25:
8
System.out.println("You are 25.");
9
break;
10
case 30:
11
System.out.println("You are 30.");
12
break;
13
default:
14
System.out.println("Age not matched.");
15
}
16
}
17
}
Output
You are 25.
Note: Regardless of its placement, the default case only gets executed if none of the other case conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic (unless you’re using a less common technique called fall-through).
Example: Using Character Wrapper
1
public class WrapperSwitchExample {
2
public static void main(String[] args) {
3
Character ch = 'c';
4
5
switch (ch) { // Extract primitive value for switch
6
case 'a':
7
System.out.println("You are a.");
8
break;
9
case 'c':
10
System.out.println("You are c.");
11
break;
12
default:
13
System.out.println("Character not matched.");
14
}
15
}
16
}
Output
You are c.
Read More:
Usage of Enum and Switch Keyword in Java
String in Switch Case in Java
Java Tutorial
Exercise:
To practice Java switch statements you can visit the page: Java Switch Case statement Practice
Conclusion
Switch statements in Java are control flow structures that allow you to execute specific blocks of code based on the value of a single expression. They can be considered an alternative to if-else-if statements and are useful for handling multiple conditions in a clean and readable manner.
Java Switch Statements- FAQs
How to use switch statements in Java?
To use switch statement in Java, you can use the following syntax:
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// … more cases
default:
// code to execute if none of the above cases match
}
*Can we pass null to a switch?
*
No, you can not pass NULL to a switch statement as they require constant expression in its case.
*Can you return to a switch statement?
No, switch statements build a control flow in the program, so it can not go back after exiting a switch case.
Flowchart of Switch-Case Statement:
Example program:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
*Some Important Rules for Java Switch Statements
*
Case values must be constants or literals and of the same type as the switch expression.
Duplicate case values are not allowed.
The break statement is used to exit from the switch block. It is optional but recommended to prevent fall-through.
The default case is optional and executes if no case matches the switch expression. It can appear anywhere within the switch block.
Break in switch case Statements:
A break statement is optional. If we omit the break, execution will continue into the next case.
It is sometimes desirable to have multiple cases without “break” statements between them.
Top comments (0)