Java switch Statement and Expression
switch chooses one path from many, based on the value of a variable. It is cleaner than many else if.
Classic switch with break
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
}
}
}
Output
Wednesday
Without break Java goes on and runs the next cases too. This is called fall through:
public class Fall {
public static void main(String[] args) {
int n = 1;
switch (n) {
case 1:
System.out.println("one");
case 2:
System.out.println("two (fell through)");
break;
case 3:
System.out.println("three");
}
}
}
Output
one
two (fell through)
Modern switch with arrows (Java 14+)
The arrow -> form has no fall through and no break. You can also group many labels with a comma.
public class Arrow {
public static void main(String[] args) {
String day = "SAT";
switch (day) {
case "MON", "TUE", "WED", "THU", "FRI" -> System.out.println("Working day");
case "SAT", "SUN" -> System.out.println("Weekend");
default -> System.out.println("Unknown");
}
}
}
Output
Weekend
Switch expression
A switch can give a value. Save it in a variable:
public class Expr {
public static void main(String[] args) {
int month = 2;
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> throw new IllegalArgumentException("Bad month: " + month);
};
System.out.println("Days: " + days);
}
}
Output
Days: 28
Many lines in a case: yield
public class Yield {
public static void main(String[] args) {
int marks = 82;
String grade = switch (marks / 10) {
case 10, 9 -> "A+";
case 8 -> {
System.out.println("Good result");
yield "A";
}
case 7 -> "B";
default -> "C";
};
System.out.println(grade);
}
}
Output
Good result
A
In a block, yield gives the value of the switch expression.
What can you switch on?
int, char, byte, short, their wrappers, String, enum values, and with modern Java also patterns (see Pattern Matching). You can not switch on long, float, double or boolean.
Note:
Prefer the arrow form in new code. It is shorter and safe from the forgotten break. Next: Java for Loop.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |