Open In App

Record Pattern with instanceof in Java 19

Last Updated : 14 May, 2023
Summarize
Comments
Improve
Suggest changes
Share
48 Likes
Like
Report

In Java, the instanceof operator is used to check whether an object is an instance of a particular class or interface. It returns a boolean value of true if the object is an instance of the specified class or interface, and false otherwise.

Example of using instanceof

Output:

Length of the String Hello world! : 13

Explanation:

In this example, we create an object obj of type Object, which is a superclass of all other classes in Java. We then use instanceof to check if obj is an instance of the String class. Since obj contains a string, the code within the if block will be executed, and we can safely cast obj to a String to access its length() method.

Record Pattern

The record pattern is a new feature introduced in Java 16, which provides a concise way to define classes whose main purpose is to store data. A record class contains a fixed set of properties and generates a constructor, getters, and other methods to access and modify these properties automatically.

Example of a record class:

// We define a record class called Person that has
// two properties: name of type String and age of type int
public record Person(String name, int age) {}

The record keyword indicates that this is a record class.

Record Pattern with instanceof 

Using the record pattern in combination with instanceof, we can simplify code that works with record classes. 

Here's an example:

Output:

Abhi is 25 years old.

Explanation:

In this example, we create an object obj of type Object that contains a Person record object. We then use the instanceof operator with a pattern matching switch statement to check if obj is an instance of Person, and if so, bind it to a new variable person of type Person. We can then access the name and age fields directly from the person.

Conclusion

The record pattern with instanceof can help simplify code that works with record classes and make it more concise and easier to read.


Article Tags :
Practice Tags :

Similar Reads