Java Switch Case
The Java switch statement selects one execution path based on the value of an expression. It is often clearer than a long if-else-if chain when one value must be compared with several fixed alternatives.
This tutorial covers the traditional colon-style Java switch statement, the role of case, break, and default, fall-through behavior, supported value types, grouped case labels, and modern switch expressions that return a value.
Java Switch Statement Syntax with case, break, and default
A switch statement contains a selector expression, one or more case labels, and an optional default label. Here is the traditional syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
// ... other cases ...
default:
// statements
}
You can also use braces around the statements in each case block to group multiple statements together:
switch (expression) {
case value1: {
// statements
break;
}
case value2: {
// statements
break;
}
default: {
// statements
}
}
Java evaluates the selector expression once and compares its result with the case labels. When a match is found, execution begins at that case. In the traditional colon-style form, execution continues until a break, return, throw, or the end of the switch block is reached. The default block runs when no case matches.
How Java Switch Case Matching Works
- case labels must be compatible: Each case value must be compatible with the selector type.
- case labels must be unique: Duplicate case constants cause a compile-time error.
- break prevents fall-through: It exits the switch after the selected case finishes.
- default is optional: It handles values not matched by any explicit case.
- case order does not affect matching: Java selects the matching label, although order affects intentional fall-through in colon-style switches.
Common selector types include byte, short, char, int, their wrapper classes, String, and enum types. A traditional constant-based switch does not use long, float, or double values as ordinary case constants.
Java Switch Case Examples
Java Switch Case with an Integer
This example demonstrates a switch statement based on an integer value. The program prints a message based on the value of the variable x.
Main.java
public class Main {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 0: {
System.out.println("x is zero.");
break;
}
case 1: {
System.out.println("x is one.");
break;
}
case 2: {
System.out.println("x is two.");
break;
}
default: {
System.out.println("x has an unexpected value.");
}
}
}
}
Output:
x is two.
The value of x is 2, so Java starts at case 2:. The message is printed, and break exits the switch before any later label can run.
Java Switch Case with a String
A Java switch can compare String values. This example normalizes the input with toLowerCase() before switching so that inputs such as Teacher and teacher reach the same case.
Main.java
public class Main {
public static void main(String[] args) {
someFunction("Teacher");
someFunction("student");
someFunction("Principal");
someFunction("Guest");
}
public static void someFunction(String role) {
switch (role.toLowerCase()) {
case "student": {
System.out.println("I'm a student.");
break;
}
case "teacher": {
System.out.println("I'm a teacher.");
break;
}
case "principal": {
System.out.println("I'm the principal.");
System.out.println("I lead the school.");
break;
}
default: {
System.out.println("Role not recognized.");
}
}
System.out.println();
}
}
Output:
I'm a teacher.
I'm a student.
I'm the principal.
I lead the school.
Role not recognized.
Each normalized string is compared with the string case labels. When none of the labels matches, the default block prints Role not recognized.
A null string cannot be processed by toLowerCase(). Validate nullable input before calling the method or before using it as the selector in a traditional switch.
Java Switch Fall-Through When break Is Missing
If break is omitted from a traditional colon-style switch, execution continues into the following case blocks. This is called fall-through. It can be intentional, but an accidental omission often produces incorrect output.
Main.java
public class Main {
public static void main(String[] args) {
int day = 3;
System.out.println("Using fall-through:");
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
case 4:
System.out.println("Thursday");
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
}
}
}
Output:
Using fall-through:
Wednesday
Thursday
Friday
The selector matches case 3:. Because cases 3 and 4 have no break, Java also executes their following statements and stops only at the break inside case 5.
Java Switch Case with a char Grade
The switch statement can also compare char values. In this example, the selected message depends on a grade stored as a character.
Main.java
public class Main {
public static void main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A': {
System.out.println("Excellent!");
break;
}
case 'B': {
System.out.println("Good job!");
break;
}
case 'C': {
System.out.println("Well done!");
break;
}
case 'D': {
System.out.println("You passed.");
break;
}
case 'F': {
System.out.println("Better try again.");
break;
}
default: {
System.out.println("Invalid grade.");
}
}
}
}
Output:
Good job!
The value of grade is 'B', so the corresponding case prints Good job! and exits the switch.
Group Multiple Java Case Labels for the Same Result
Several case labels can share one block when they require the same action. In a traditional switch, place the labels one after another and add statements only after the final label.
public class Main {
public static void main(String[] args) {
int month = 4;
switch (month) {
case 4:
case 6:
case 9:
case 11:
System.out.println("This month has 30 days.");
break;
default:
System.out.println("This month does not have 30 days.");
}
}
}
Output:
This month has 30 days.
This form uses fall-through deliberately. Months 4, 6, 9, and 11 all reach the same print statement.
Java Switch Expression with Arrow Case Labels
A modern Java switch can be used as an expression that produces a value. Arrow labels use -> and do not fall through, so a separate break is not needed for each arm.
public class Main {
public static void main(String[] args) {
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
System.out.println(type);
}
}
Output:
Weekend
The expression assigns exactly one result to type. Comma-separated labels let several values share one arrow arm. A switch expression must provide a result for every possible selector value, which is why a default arm is commonly included.
Use yield in a Multi-Statement Java Switch Expression
When an arrow arm needs more than one statement, enclose the arm in braces and use yield to provide the value of the switch expression.
public class Main {
public static void main(String[] args) {
int score = 82;
String result = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> {
System.out.println("Score is in the eighties.");
yield "B";
}
case 7 -> "C";
case 6 -> "D";
default -> "F";
};
System.out.println("Grade: " + result);
}
}
Output:
Score is in the eighties.
Grade: B
The yield "B"; statement supplies the value returned by that switch arm. It is not the same as break: break exits a statement, whereas yield provides a result from a switch expression block.
Java Switch Statement vs Switch Expression
| Feature | Traditional switch statement | Switch expression |
|---|---|---|
| Primary purpose | Run statements | Produce a value |
| Typical labels | case value: | case value -> |
| Fall-through | Possible with colon labels | Not used with arrow labels |
| Exit or result keyword | Usually break | yield for a block arm |
| Assignment | Usually assign inside individual cases | Assign the switch result directly |
When to Use Java Switch Instead of if-else
Use switch when one selector is compared against distinct values or patterns and each alternative has a clear action. Use if-else when decisions depend on ranges, several unrelated variables, or compound boolean conditions such as age >= 18 && hasPermission.
- Use switch for menu options, status codes, enum constants, command names, and other discrete choices.
- Use if-else for inequalities, numeric ranges, and conditions joined with
&&or||. - Prefer arrow labels when fall-through is not required.
- Use intentional fall-through only when it makes the shared behavior easier to understand.
Common Java Switch Case Errors
- Missing break: A colon-style case continues into later cases unless control exits the switch.
- Duplicate case value: Two labels cannot use the same constant.
- Non-constant case label: Traditional case labels must be compile-time constants, enum constants, or otherwise valid labels for the switch form being used.
- Null selector: Calling a method such as
toLowerCase()on null fails before the switch runs, and unsupported null handling can also throw an exception. - Incomplete switch expression: Every possible path must produce a value or complete abruptly by throwing an exception.
- Using switch for ranges: A chain of range-based
if-elseconditions is usually clearer than listing many individual values.
Java Switch Case Editorial QA Checklist
- Confirm that every case label is valid for the selector type.
- Check colon-style cases for accidental fall-through and missing
breakstatements. - Verify that grouped labels intentionally share the same statements.
- Ensure every switch expression path returns a compatible value.
- Test the
defaultpath with an unmatched selector value. - Check nullable string or wrapper selectors before switching on them.
Java Switch Case Questions
Is the default case required in a Java switch?
No. The default label is optional in a switch statement. However, it is useful for handling unexpected values. A switch expression must still be exhaustive, so a default arm is often needed unless the compiler can determine that all possible values are covered.
What happens when break is omitted from a Java switch case?
In a colon-style switch, execution falls through into the statements under later case labels until it reaches a control-transfer statement or the end of the switch. Arrow-style case arms do not fall through.
Can Java switch work with String values?
Yes. A switch can compare strings. Matching is case-sensitive, so normalize the input first when case-insensitive behavior is required. Also handle a possible null value before calling methods on the string.
Can multiple case labels run the same Java code?
Yes. In a traditional switch, place multiple labels before one shared block. With arrow labels, separate the values with commas, as in case 6, 7 -> "Weekend";.
What is the difference between break and yield in Java switch?
break exits a switch statement or loop. yield supplies the result of a multi-statement block inside a switch expression.
Java Switch Case Summary
In this Java Tutorial, we learned how Java switch case matching works with integers, strings, and characters. We also covered break, default, fall-through, grouped case labels, arrow-style switch expressions, and yield.
TutorialKart.com