Consider another example, this one evaluating decimal precision:
double measurement = 17.5;
if (measurement instanceof float simpleMeasurement) {
System.out.println("No precision loss: " + simpleMeasurement);
} else {
System.out.println("Requires double precision");
}
This verifies if the double
value can be represented as a float
without precision loss.
Here’s an example using primitive type pattern matching with text characters:
int codePoint = 90;
if (codePoint instanceof char symbol) {
System.out.println("This represents: '" + symbol + "'");
} else {
System.out.println("Not a valid character code");
}
The output from this code would be: This represents: ‘Z’
, because 90 is the ASCII/Unicode value for Z.
Finally, here’s a demonstration showing multiple type compatibility checks:
void examineNumber(long input) {
System.out.println("Examining: " + input);
if (input instanceof byte b)
System.out.println("Fits in a byte variable: " + b);
if (input instanceof short s)
System.out.println("Fits in a short variable: " + s);
if (input >= 0 && input <= 65535 && input instanceof char c)
System.out.println("Represents character: '" + c + "'");
if (input instanceof int i)
System.out.println("Fits in an int variable: " + i);
}
When called with examineNumber(77)
, this code would output all four messages, including that 77 represents the character ‘M’
.
When to use primitive type pattern matching
Primitive type pattern matching is particularly valuable for the following uses:
- Validating user input against acceptable ranges.
- Converting between numeric formats while avoiding data loss.
- Working with character encoding in text processing.
- Making numeric type conversions more readable and safe.
Conclusion
Pattern matching represents a significant evolution in Java’s syntax, bringing more expressive and concise ways to work with data. By combining type checking, casting, and data extraction into unified operations, it reduces boilerplate and makes code more readable and maintainable.
Java developers can now write cleaner code when working with polymorphic data, nested structures, and conditional processing. Basic pattern matching features (like enhanced instanceof
) are available from Java 16 onward, while more advanced capabilities (like record patterns and guarded patterns) came up in Java 21.
As this feature continues to mature in future releases, it will further strengthen Java’s position as a language that balances performance, safety, and expressiveness. If you haven’t played with pattern matching yet, create some code and run a few tests to absorb the knowledge. The best way to acquire a skill is to put it into practice.