🏷 Pattern Matching
7 patterns
Topic: Pattern Matching
All Java patterns related to Pattern Matching — java.evolved
Language
Exhaustive switch without default
Old
// Must add default even though
// all cases are covered
double area(Shape s) {
if (s instanceof Circle c)
return Math.PI * c.r() * c.r();
else if (s instanceof Rect r)
return r.w() * r.h();
else throw new IAE();
}
Modern
// sealed Shape permits Circle, Rect
double area(Shape s) {
return switch (s) {
case Circle c ->
Math.PI * c.r() * c.r();
case Rect r ->
r.w() * r.h();
}; // no default needed!
}
hover to see modern →
JDK 21+
learn more →
Language
Guarded patterns with when
Old
if (shape instanceof Circle) {
Circle c = (Circle) shape;
if (c.radius() > 10) {
return "large circle";
} else {
return "small circle";
}
} else {
return "not a circle";
}
Modern
return switch (shape) {
case Circle c
when c.radius() > 10
-> "large circle";
case Circle c
-> "small circle";
default -> "not a circle";
};
hover to see modern →
JDK 21+
learn more →
Language
Pattern matching for instanceof
Old
if (obj instanceof String) {
String s = (String) obj;
int length = s.length();
// do something with 'length'
}
Modern
if (obj instanceof String s) {
int length = s.length();
// do something with 'length'
}
hover to see modern →
JDK 16+
learn more →
Language
Pattern matching in switch
Old
String format(Object obj) {
if (obj instanceof Integer i)
return "int: " + i;
else if (obj instanceof Double d)
return "double: " + d;
else if (obj instanceof String s)
return "str: " + s;
return "unknown";
}
Modern
String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Double d -> "double: " + d;
case String s -> "str: " + s;
default -> "unknown";
};
}
hover to see modern →
JDK 21+
learn more →
Language
Primitive types in patterns
Old
String classify(int code) {
if (code >= 200 && code < 300)
return "success";
else if (code >= 400 && code < 500)
return "client error";
else
return "other";
}
Modern
String classify(int code) {
return switch (code) {
case int c when c >= 200
&& c < 300 -> "success";
case int c when c >= 400
&& c < 500 -> "client error";
default -> "other";
};
}
hover to see modern →
JDK 25+
learn more →
Language
Record patterns (destructuring)
Old
if (obj instanceof Point) {
Point p = (Point) obj;
int x = p.getX();
int y = p.getY();
System.out.println(x + y);
}
Modern
if (obj instanceof Point(int x, int y)) {
IO.println(x + y);
}
hover to see modern →
JDK 21+
learn more →
Language
Unnamed variables with _
Old
try {
parse(input);
} catch (Exception ignored) {
log("parse failed");
}
map.forEach((key, value) -> {
process(value); // key unused
});
Modern
try {
parse(input);
} catch (Exception _) {
log("parse failed");
}
map.forEach((_, value) -> {
process(value);
});
hover to see modern →
JDK 22+
learn more →