Home  >  Core Java

Java Pattern Matching for instanceof

By Arvind Rai, August 02, 2021
This page will walk through Java pattern matching for instanceof operator. The instanceof operator has been enhanced. Now it performs following steps.
The instanceof operator
1. Matches whether an object has a particular structure.
2. Extracts data from that object if there is a match.

For the pattern matching feature, the instanceof operator has been enhanced to conditionally extract data from objects. With this feature the code will be more concise.
Find the sample code to use enhanced instanceof operator.
if (shape instanceof Rectangle r) {
  r.length = 5;
  r.width = 3;
  System.out.println(r.getArea());
} else if (shape instanceof Square s) {
  s.side = 4;
  System.out.println(s.getArea());
} 
The pattern matching for instanceof operator was introduced in Java 14 as preview feature and previewed again in Java 15. The pattern matching for instanceof operator has been adopted as permanent language feature in Java 16 (JEP 394).



Using Enhanced instanceof Operator

Look into the below code snippet for enhanced instanceof operator.
if (shape instanceof Rectangle r) {
  //
} 
The instanceof operator performs two steps.
1. Matches whether the object shape has the structure of Rectangle class type. If no match, then it returns false boolean value.
2. If structure is matched then object shape is typecast to Rectangle class and assigned to variable r.
The above same operation is achieved by old instanceof operator as following.
if (shape instanceof Rectangle) {
  Rectangle r = (Rectangle) shape; 
  //
} 
Find the complete example to use enhanced instanceof operator.
MyApp.java
package com.concretepage;
interface Shape {
}
class Rectangle implements Shape {
  int length;
  int width;
  public int getArea() {
	return length * width;
  }
}
class Square implements Shape {
  int side;
  public int getArea() {
	return side * side;
  }
}
public class MyApp {
  public static void main(String[] args) {
	Shape ob = new Rectangle();
	calculateArea(ob);
	ob = new Square();
	calculateArea(ob);	
  }
  static void calculateArea(Shape shape) {
	if (shape instanceof Rectangle r) {
	  r.length = 5;
	  r.width = 3;
	  System.out.println(r.getArea());
	} else if (shape instanceof Square s) {
	  s.side = 4;
	  System.out.println(s.getArea());
	}
  }
} 

Understanding Pattern Variable Scope

1. The pattern variable can be used where the program can reach only if the instanceof operator is true.
if (shape instanceof Rectangle r) {
 //r can be used here.
} else if (shape instanceof Square s) {
 //r cannot be used here.
 //s can be used here.
} else {
 //r cannot be used here.
 //s cannot be used here.
} 
2. The pattern variable can be used in the else block in the case when instanceof operator returns true but if condition is false.
if (!(shape instanceof Rectangle r)) {
  //r cannot be used here.
} else {
  //r can be used here.
  r.length = 5;
  r.width = 3;	  
  System.out.println(r.getArea());  
} 
3. The pattern variable can be used in the expression of if and else if statement with AND (&&) operator but not with OR (||) operator.
Find the code snippet with && operator.
if (shape instanceof Rectangle r && r.length > 10) { // Compiles successfully.
  //
} 
We know that && operator is short-circuiting and hence if instanceof operator returns false then && block will not execute but || block will execute and that is why we cannot use pattern variable with ||. The following code will not compile.
if (shape instanceof Rectangle r || r.length > 10) { // Compilation error.
  //
} 

References

Pattern Matching for instanceof
JEP 394: Pattern Matching for instanceof
POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us