// Old way (pre-Java 16)
void process(Object o) {
if (o instanceof String) {
String s = (String) o; // separate cast
System.out.println(s.toUpperCase());
}
}
// New way (Java 16+)
void process2(Object o) {
if (o instanceof String s) { // binding pattern
System.out.println(s.toUpperCase());
}
}
// Combined with && — s is in scope on the right
void process3(Object o) {
if (o instanceof String s && s.length() > 5) {
System.out.println("long string: " + s);
}
}
// Record deconstruction (Java 21+)
record Point(int x, int y) {}
void describe(Object o) {
if (o instanceof Point(int x, int y)) {
System.out.printf("x=%d y=%d%n", x, y);
}
}
Create a free account and build your private vault. Share publicly whenever you want.