How To Get Started With New Pattern Matching in Java 21
Dive into pattern matching, a powerful new feature in Java 21 that lets you easily deconstruct and analyze data structures. Follow this tutorial for examples.
Join the DZone community and get the full member experience.
Join For FreeJava 21 just got simpler!
Want to write cleaner, more readable code? Dive into pattern matching, a powerful new feature that lets you easily deconstruct and analyze data structures. This article will explore pattern matching with many examples, showing how it streamlines normal data handling and keeps your code concise.
Examples of Pattern Matching
Pattern matching shines in two key areas. First, the pattern matching feature of switch statements replaces the days of long chains of if
statements, letting you elegantly match the selector expression against various data types, including primitives, objects, and even null. Secondly, what if you need to check an object's type and extract specific data? The pattern matching feature of instance expressions simplifies this process which allows you to confirm if an object matches a pattern and, if so, conveniently extract the desired data.
Let’s take a look at more examples of pattern matching in Java code.
Pattern Matching With Switch Statements
public static String getAnimalSound(Animal animal) {
return switch (animal) {
case Dog dog -> "woof";
case Cat cat -> "meow";
case Bird bird -> "chirp";
case null -> "No animal found!";
default -> "Unknown animal sound";
};
}
- Matches selector expressions with types other than integers and strings
- Uses type patterns (
case Dog dog
) to check and cast types simultaneously - Handles null directly within the switch block (
case null
) - Employs arrow syntax (
->
) for concise body expressions
Pattern Matching With instanceof
if (object instanceof String str) {
System.out.println("The string is: " + str);
} else if (object instanceof Integer num) {
System.out.println("The number is: " + num);
} else {
System.out.println("Unknown object type");
}
- Combines type checking and casting in a single expression
- Introduces a pattern variable (
str, num
) to capture the object's value. - Avoids explicit casting (
String str = (String) object
).
Pattern Matching With Primitive Types
int number = 10;
switch (number) {
case 10:
System.out.println("The number is 10.");
break;
case 20:
System.out.println("The number is 20.");
break;
case 30:
System.out.println("The number is 30.");
break;
default:
System.out.println("The number is something else.");
}
Pattern matching with primitive types doesn't introduce entirely new functionality but rather simplifies existing practices when working with primitives in switch statements.
Pattern Matching With Reference Types
String name = "Daniel Oh";
switch (name) {
case "Daniel Oh":
System.out.println("Hey, Daniel!");
break;
case "Jennie Oh":
System.out.println("Hola, Jennie!");
break;
default:
System.out.println("What’s up!");
}
- Pattern matching with reference types makes code easier to understand and maintain due to its clear and concise syntax.
- By combining type checking and extraction in one step, pattern matching reduces the risk of errors associated with explicit casting.
- More expressive switch statements:
- Switch statements become more versatile and can handle a wider range of data types and scenarios.
Pattern Matching With null
Object obj = null;
switch (obj) {
case null:
System.out.println("The object is null.");
break;
default:
System.out.println("The object is not null.");
}
- Before Java 21, switch statements would throw a
NullPointerException
if the selector expression wasnull
. Pattern matching allows a dedicatedcase null
clause to handle this scenario gracefully. - By explicitly checking for null within the switch statement, you avoid potential runtime errors and ensure your code is more robust.
- Having a dedicated
case null
clause makes the code's intention clearer compared to needing an external null check before the switch. - Java's implementation is designed not to break existing code. If a switch statement doesn't have a
case null
clause, it will still throw aNullPointerException
as before, even if a default case exists.
Pattern Matching With Multiple Patterns
List<String> names = new ArrayList<>();
names.add("Daniel Oh");
names.add("Jennie Oh");
for (String name : names) {
switch (name) {
case "Daniel Oh", "Jennie Oh":
System.out.println("Hola, " + name + "!");
break;
default:
System.out.println("What’s up!");
}
}
- Unlike traditional switch statements, pattern matching considers the order of cases.
- The first case with a matching pattern is executed.
- Avoid unreachable code by ensuring subtypes don't appear before their supertypes in the pattern-matching cases.
Conclusion
Pattern matching is a powerful new feature in Java 21 that can make your code more concise and readable. It is especially useful for working with complex data structures with key benefits:
- Improved readability: Pattern matching makes code more readable by combining type checking, data extraction, and control flow into a single statement. This eliminates the need for verbose if-else chains and explicit casting.
- Conciseness: Code becomes more concise by leveraging pattern matching's ability to handle multiple checks and extractions in a single expression. This reduces boilerplate code and improves maintainability.
- Enhanced type safety: Pattern matching enforces type safety by explicitly checking and potentially casting the data type within the switch statement or instance expression. This reduces the risk of runtime errors caused by unexpected object types.
- Null handling: Pattern matching allows for the explicit handling of null cases directly within the switch statement. This eliminates the need for separate null checks before the switch, improving code flow and reducing the chance of null pointer exceptions.
- Flexibility: Pattern matching goes beyond basic types. It can handle complex data structures using record patterns (introduced in Java 14). This allows for more expressive matching logic for intricate data objects.
- Modern look and feel: Pattern matching aligns with modern functional programming paradigms, making Java code more expressive and aligned with other languages that utilize this feature.
Overall, pattern matching in Java 21 streamlines data handling, improves code clarity and maintainability, and enhances type safety for a more robust and developer-friendly coding experience.
Opinions expressed by DZone contributors are their own.
Comments