Switch & Records
Original switch:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Limitations:
- Switch could only be used with primitive types (int, char, byte, short) and later with enums.
- Required break to avoid falling through cases unintentionally.
Enums in Switch
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day day = Day.TUESDAY;
switch (day) {
case MONDAY:
System.out.println("Monday");
break;
case TUESDAY:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Switch with Strings
String day = "Tuesday";
switch (day) {
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Switch Expressions
int day = 2;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid day";
};
System.out.println(dayName);
- The switch statement can now be used as an expression that returns a value.
- Arrow (->) syntax introduced for cleaner case expressions.
- The break statement is no longer needed in this context.
- Multiple case labels (case 1, 7 ->) can be grouped together to handle cases more concisely.
Pattern Matching
Object obj = 123;
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown type";
};
System.out.println(result);
- Switch can now match based on the type of the object being switched.
- Automatic casting based on the type pattern (e.g., Integer i).
Expanded Pattern
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
Shape shape3 = new Triangle(3, 4);
static double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius(); // Calculate area for Circle
case Rectangle r -> r.width() * r.height(); // Calculate area for Rectangle
case Triangle t when t.base() > 0 && t.height() > 0 -> 0.5 * t.base() * t.height(); // Calculate area for Triangle with guard condition
default -> throw new IllegalArgumentException("Unknown shape: " + shape);
};
}
- You can de-structure records in the switch expression, making it easier to work with data classes.
- You can add additional conditions to your case statements, allowing for more granular control over the flow of logic.
- Simplified handling of complex data types like sealed types and records.