DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • The Beauty of Java Optional and Either
  • All Things Java 8 [Tutorials]
  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Mastering Exception Handling in Java Lambda Expressions

Trending

  • Elevate Your Terminal Game: Hacks for a Productive Workspace
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Understanding Kernel Monitoring in Windows and Linux
  • Automated Data Extraction Using ChatGPT AI: Benefits, Examples
  1. DZone
  2. Coding
  3. Java
  4. How To Get Started With New Pattern Matching in Java 21

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.

By 
Daniel Oh user avatar
Daniel Oh
DZone Core CORE ·
Mar. 26, 24 · Tutorial
Like (10)
Save
Tweet
Share
1.8K Views

Join the DZone community and get the full member experience.

Join For Free

Java 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

Java
 
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

Java
 
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

Java
 
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

Java
 
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

Java
 
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 was null. Pattern matching allows a dedicated case 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 a NullPointerException as before, even if a default case exists.

Pattern Matching With Multiple Patterns

Java
 
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.

Extracting Data From Patterns

Java
 
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

for (Integer number : numbers) {
    switch (number) {
        case Dog(String name):
            System.out.println("Hello, " + name + "!");
            break;
        default:
            System.out.println("Hello stranger!");
    }
}


In the last example, we are using pattern matching to extract the dog's name from the Dog object.

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.

Functional programming Type safety Java (programming language) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • The Beauty of Java Optional and Either
  • All Things Java 8 [Tutorials]
  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Mastering Exception Handling in Java Lambda Expressions

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: