Works with: int, byte, short, char
int day = 2;
String result;
switch (day) {
case 1:
result = "Monday";
break;
case 2:
result = "Tuesday";
break;
default:
result = "Invalid";
}
System.out.println(result);✅ Output:
Tuesday
🧠 Notes: Needs break to prevent fall-through.
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day today = Day.TUESDAY;
switch (today) {
case MONDAY:
System.out.println("Start of week");
break;
case TUESDAY:
System.out.println("Second day");
break;
default:
System.out.println("Midweek or later");
}✅ Output:
Second day
🧠 Notes: Enum constants (MONDAY, TUESDAY, etc.) can be used as case labels.
String command = "start";
switch (command) {
case "start":
System.out.println("Application starting...");
break;
case "stop":
System.out.println("Application stopping...");
break;
default:
System.out.println("Unknown command");
}✅ Output:
Application starting...
🧠 Notes: Behind the scenes, Java uses String.hashCode() and equals checks.
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> {
System.out.println("Weekend logic here");
yield "Weekend"; // return value from block
}
default -> "Invalid";
};
System.out.println(type);✅ Output:
Weekend logic here
Weekend
🧠 Notes:
switchcan now return values.yieldused for block-style cases.
static String describe(Object obj) {
return switch (obj) {
case String s -> "Short string";
case Integer i -> "Integer: " + i;
case null -> "Null value";
default -> "Unknown type";
};
}
public static void main(String[] args) {
System.out.println(describe("Hello"));
System.out.println(describe("Welcome"));
System.out.println(describe(42));
System.out.println(describe(null));
}✅ Output:
Short string
Long string
Integer: 42
Null value
🧠 Notes:
switchnow supports type matching, guarded patterns, and null-safe handling.- Fully standardized in JDK 21 (no preview flags needed).
| JDK | Feature | Example Concept | Highlight |
|---|---|---|---|
| 1.0 | Classic switch | Works on int, needs break |
Basic control flow |
| 5 | Enum support | case MONDAY: |
Type-safe enum usage |
| 7 | String support | case "start": |
String-based branching |
| 14 | Switch expressions + yield | yield "Weekend"; |
Expression switch, returns value |
| 21 | Pattern matching | case String s && s.length()>5 -> ... |
Type-safe, null-safe, concise |