In Part 1, we learned how the if-else statement helps Java make decisions based on boolean conditions.
However, when you need to choose between multiple fixed values, writing long chains of if-else if-else statements can make your code difficult to read and maintain.
That's where the switch statement comes in.
What Is the switch Statement?
The switch statement allows you to execute different blocks of code based on the value of an expression.
It is often cleaner and more readable than multiple if-else statements when comparing a variable against several possible values.
Example
Instead of writing
String day = "MONDAY";
if (day.equals("MONDAY")) {
System.out.println("Start of the work week");
}
else if (day.equals("TUESDAY")) {
System.out.println("Second working day");
}
else if (day.equals("WEDNESDAY")) {
System.out.println("Midweek");
}
else {
System.out.println("Weekend or another day");
}
You can write
String day = "MONDAY";
switch (day) {
case "MONDAY":
System.out.println("Start of the work week");
break;
case "TUESDAY":
System.out.println("Second working day");
break;
case "WEDNESDAY":
System.out.println("Midweek");
break;
default:
System.out.println("Weekend or another day");
}
The switch version is easier to read and maintain.
Syntax
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
Supported Data Types
The types supported by switch have evolved over different Java versions.
| Java Version | Supported Types |
|---|---|
| Java 1.4 and earlier |
byte, short, char, int
|
| Java 5 | Wrapper classes (Byte, Short, Character, Integer) and enum
|
| Java 7 and later | String |
Note: Types such as
long,float,double, andbooleanare not supported in a traditionalswitchstatement.
Rule 1: Curly Braces Are Mandatory
Unlike an if statement, curly braces cannot be omitted.
Correct
int choice = 1;
switch (choice) {
case 1:
System.out.println("One");
}
Incorrect
switch (choice)
case 1:
System.out.println("One");
Compile-time error
Rule 2: case and default Are Optional
A switch statement may contain:
- Only
case - Only
default - Both
- Neither
Even an empty switch is valid.
int option = 1;
switch (option) {
}
This compiles successfully.
Rule 3: Every Statement Must Belong to a case or default
Incorrect
int choice = 1;
switch (choice) {
System.out.println("Hello");
case 1:
System.out.println("One");
}
Compile-time error
case, default, or '}' expected
Every executable statement inside a switch block must belong to a case or default label.
Rule 4: Every case Label Must Be a Compile-Time Constant
Correct
int choice = 2;
switch (choice) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
}
Incorrect
int option = 2;
int value = 2;
switch (option) {
case value:
System.out.println("Two");
}
Compile-time error
constant expression required
Why?
The compiler does not know the value of value during compilation.
Using final
int option = 2;
final int VALUE = 2;
switch (option) {
case VALUE:
System.out.println("Two");
}
This works because a final variable initialized with a constant becomes a compile-time constant.
Rule 5: Case Labels Must Be Within Range
Consider a byte.
byte number = 10;
switch (number) {
case 10:
System.out.println("Ten");
case 100:
System.out.println("Hundred");
}
This compiles because both values fit into the range of a byte.
Now try
byte number = 10;
switch (number) {
case 1000:
System.out.println("Thousand");
}
Compile-time error
possible lossy conversion from int to byte
Since 1000 cannot fit into a byte, Java rejects it.
Rule 6: Duplicate case Labels Are Not Allowed
char letter = 'a';
switch (letter) {
case 97:
System.out.println("ASCII");
case 'a':
System.out.println("Character");
}
Compile-time error
duplicate case label
Why?
Because
'a' = 97
Both labels represent the same value.
Understanding Fall-Through
One of the most important concepts in a traditional switch statement is fall-through.
When a matching case is found, execution continues until:
- a
breakstatement is encountered, or - the switch block ends.
Example
int number = 0;
switch (number) {
case 0:
System.out.println("Zero");
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
default:
System.out.println("Default");
}
Output
Zero
One
Why?
Execution starts at case 0.
Since there is no break, execution continues into case 1.
The break stops further execution.
Output Table
| Value | Output |
|---|---|
0 |
Zero, One |
1 |
One |
2 |
Two, Default |
3 |
Default |
Why Is Fall-Through Useful?
Sometimes multiple cases should perform the same action.
Example
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("Pass");
break;
default:
System.out.println("Fail");
}
Output
Pass
This avoids duplicate code.
The default Case
The default block executes when no case matches.
int option = 10;
switch (option) {
case 1:
System.out.println("One");
break;
default:
System.out.println("Invalid option");
}
Output
Invalid option
Does default Have to Be Last?
No.
Although placing it last is the standard convention, Java allows it anywhere.
Example
int number = 3;
switch (number) {
default:
System.out.println("Default");
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
}
Output
Default
One
Since default matches first and there is no break, execution falls through into the next case.
switch with enum
Support for enum was introduced in Java 5.
enum Coffee {
ESPRESSO,
LATTE,
CAPPUCCINO,
AMERICANO
}
Coffee coffee = Coffee.CAPPUCCINO;
switch (coffee) {
case ESPRESSO:
System.out.println("Strong coffee");
break;
case LATTE:
System.out.println("Milk coffee");
break;
case CAPPUCCINO:
System.out.println("Foamy coffee");
break;
case AMERICANO:
System.out.println("Black coffee");
break;
}
Output
Foamy coffee
Notice that we write
case CAPPUCCINO:
not
case Coffee.CAPPUCCINO:
Case labels must use unqualified enum constants.
switch with String
Java 7 introduced support for String.
String browser = "Chrome";
switch (browser) {
case "Chrome":
System.out.println("Google Chrome");
break;
case "Firefox":
System.out.println("Mozilla Firefox");
break;
default:
System.out.println("Unknown Browser");
}
Output
Google Chrome
Common Beginner Mistakes
Forgetting break
Without break, execution falls through into the next case.
Using Variables in case
Incorrect
int value = 10;
case value:
Only compile-time constants are allowed.
Using Unsupported Types
Incorrect
double price = 99.5;
switch (price) {
}
Compile-time error.
Traditional switch does not support double.
Writing Statements Before the First case
Every executable statement must belong to a case or default.
Best Practices
- Use
switchwhen comparing one variable against many discrete values. - Always include a
defaultcase unless every possible value is handled. - Use
breakunless fall-through is intentional. - Group related cases together to avoid duplicate code.
- Prefer meaningful enum names and string constants.
Quick Memory Trick 🧠
Remember the 4 C's of switch:
- Compare one value.
-
Choose a matching
case. -
Continue until
break. -
Otherwise execute
default.
Key Takeaways
-
switchimproves readability when handling multiple fixed values. - Curly braces are mandatory.
-
caselabels must be compile-time constants. - Duplicate case labels are not allowed.
- Fall-through occurs when
breakis omitted. -
defaultexecutes when no case matches. - Traditional
switchsupports primitives (byte,short,char,int), wrapper classes,enum, andString. -
long,float,double, andbooleanare not supported.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)