search
HomeJavajavaTutorialPattern Matching and Records Changes in Java Every Java Developer Must Know

Pattern Matching and Records Changes in Java  Every Java Developer Must Know

With the release of Java 16, a major improvement was introduced with the introduction of Records (JEP 395), which allowed for a simpler and more concise way to declare classes that are primarily used to carry data. This improvement has now been further enhanced in Java 21, with the addition of Pattern Matching and Records (JEP 406). This new feature allows for the use of pattern matching to test whether a value is an instance of a Record class and extract its components in a more streamlined way. In this article, we will explore the changes brought about by Pattern Matching and Records in Java 21 and how it can benefit Java developers.

Records as Transparent Carriers for Data
Records, introduced in Java 16, are classes that are primarily used to store and carry data. They are transparent carriers, meaning that their main purpose is to hold data, and all other functionality such as constructors, methods, and equals/hashCode methods, are generated automatically by the compiler, based on the data fields defined in the record. This makes them ideal for use in scenarios where data needs to be serialized or sent over the network.

Consider the example of a Line class that defines two X and Y coordinates:

record Line(int x, int y) {}

To use this class, we can simply create an instance of the Line class and access its data fields using the built-in component accessor methods, x() and y():

Line line = new Line(0, 10);
int x = line.x();
int y = line.y();
System.out.println("X: " + x + ", Y: " + y); // Output: X: 0, Y: 10

Pattern Matching with Records
In Java 21, Pattern Matching has been added which makes it possible to test whether a value is an instance of a Record class and extract its components in a more streamlined way. This feature is especially useful when dealing with large codebases that use Records extensively.

Consider the following example where we want to test whether an object is an instance of the Line class and extract its components:

static void length(Object obj) {
if (obj instanceof Line l) {
int x = l.x();
int y = l.y();
System.out.println(y-x);
}
}
As you can see, we have used a type pattern to test whether the object is an instance of Point and if so, we have extracted its components by invoking the built-in component accessor methods. While this code works, it can be further simplified with the use of a record pattern in Java 21.

With record pattern, we can not only test whether a value is an instance of a Record class, but we can also extract its components in a single line of code. This is achieved by lifting the declaration of local variables for the extracted components into the pattern itself, and initializing those variables by invoking the accessor methods when the value is matched against the pattern.

Consider the following code that uses a record pattern:

static void length(Object obj) {
if (obj instanceof Line(int x, int y)) {
System.out.println(y-x);
}
}
This code is much more concise and readable. We have eliminated the need for creating a new object and invoking its component accessor methods to get the data. The record pattern directly extracts and initializes the components for us, making our code more streamlined.

Nested Record Patterns
One of the major challenges faced by developers is dealing with complex object graphs and extracting data from them. This is where the real power of pattern matching comes in, as it allows us to scale elegantly and match more complicated object graphs.

Consider the following classes: Employee, Department (enum), and Company (record). We can use a record pattern to extract the Department of an Employee from a Company object:

// As of Java 21
static void printEmployeeDepartment(Company c, String name) {
if (c instanceof Company(Department dept, List employees)) {
for (Employee e : employees) {
if (e.getName().equals(name)) {
System.out.println(name + " is in " + dept + " department.");
return;
}
}
}
System.out.println(name + " not found.");
}
In this example, we are using nested patterns to extract the Department of an Employee from a Company object. We check if the given Company object has a Department and a list of Employees, and then loop through the list to find the Employee with the given name. If the Employee is found, we print their department. If not, we print a message saying that the Employee was not found.

Nested patterns can also be used in situations where we want to match and deconstruct multiple values at once. Consider the following example where we want to check if a given coordinate is located inside a rectangle:

//As of Java 21
record Point(double x, double y) {}

record Rectangle(Point upperLeft, Point lowerRight) {}

// check if given point is located inside the given rectangle
static boolean isPointInsideRectangle(Point p, Rectangle r) {
if (r instanceof Rectangle(Point(var x1, var y1), Point(var x2, var y2))) {
if (p.x() > x1 && p.y() > y1 && p.x() return true;
}
}
return false;
}

In this example, we are using nested patterns to check whether a given Point object falls within the bounds of a given Rectangle object. The nested pattern allows us to access the x and y coordinates of the upper-left and lower-right points of the rectangle without having to write multiple lines of code.

In conclusion, with the addition of Pattern Matching and Records (JEP 406) in Java 21, there is a significant improvement in how we can handle and extract data from complex objects. This feature greatly simplifies code and makes it more readable and concise. It also helps in handling failure scenarios where the pattern match might fail. With these changes, Java 21 continues to make the code more streamlined and improves the development experience for Java developers.

Upgrade your Java 21 skills with MyExamCloud's Java SE 21 Developer Professional Practice Tests. Develop and test your knowledge to be a Java 21 expert.

The above is the detailed content of Pattern Matching and Records Changes in Java Every Java Developer Must Know. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools