Modern Java 8+ Features · Modern Java (10–21)
Modern Java: switch that returns a value with arrows (no break needed), and instanceof that checks and names a type in one step.
public class ModernSwitchDemo {
static String kind(int day) {
return switch (day) { // switch as an expression: it gives a value
case 6, 7 -> "weekend";
case 1, 2, 3, 4, 5 -> "weekday";
default -> "unknown";
};
}
static String describe(Object o) {
if (o instanceof String s) { // check the type and name it in one go
return "text of length " + s.length();
} else if (o instanceof Integer n && n > 100) {
return "big number";
}
return "something else";
}
public static void main(String[] args) {
String d6 = kind(6);
String d2 = kind(2);
String a = describe("hello");
String b = describe(500);
System.out.println(d6 + " " + d2 + " " + a + " " + b);
}
}kind(), with day = 6. It gets its own variables on the stack. The program starts in main. args holds its command-line arguments (none here).kind() has finished, so its variables are gone.d6.kind(), with day = 2. It gets its own variables on the stack.switch (day) { // switch as an expression: it gives a value.kind() has finished, so its variables are gone.d2.describe(), with o = "hello". It gets its own variables on the stack.o instanceof String s checks the type and, if it matches, creates s already cast to String.describe() has finished, so its variables are gone.a.describe(), with o = 500. It gets its own variables on the stack.if (o instanceof String s) { // check the type and name it in one go.describe() has finished, so its variables are gone.b.weekend weekday text of length 5 big number.