Pattern Matching for instanceof (introduced in Java 16)
Pattern matching simplifies code that checks types and performs casts. It allows you to combine type checking and type casting into a single operation. Here's an example:
if (obj instanceof String str) {
System.out.println(str.length()); // Safe to access str as a String
} else {
System.out.println("Not a string.");
}
No comments:
Post a Comment