Record Pattern with instanceof in Java 19
Last Updated :
14 May, 2023
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
Java
public class Example {
public static void main(String[] args)
{
Object obj = new String( "Hello, world!" );
if (obj instanceof String) {
String str = (String)obj;
System.out.println(
"Length of the String Hello world! : "
+ str.length());
}
}
}
|
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:
Java
public class Example {
public static void main(String[] args)
{
Person obj = new Person( "Abhi" , 25 );
if (obj instanceof Person) {
Person person = (Person)obj;
int age = person.age();
String name = person.name();
System.out.println(name + " is " + age
+ " years old." );
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age)
{
this .name = name;
this .age = age;
}
public String name() { return name; }
public int age() { return age; }
}
|
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.
Share your thoughts in the comments
Please Login to comment...