Java 16 – Pattern matching for instanceof

We all have used instanceof check with a subsequent cast to the desired type and in this process, we are doing two operations:

  • validating whether the object we have is of the desired type using instanceof
  • when the validation is true then we cast the object to the desired type and proceed with the operations.

This would translate to the below code:

Object obj = "This is string";
if(obj instanceof String){
	String str = (String)obj;
	System.out.println(str.toUpperCase());
}

A new language enhancement was introduced in Java 16 via the JEP 394 to achieve the above two operations in a single line of code as shown below:

Object obj = "This is string";
if(obj instanceof String str){
	System.out.println(str.toUpperCase());
}

The instanceof operation is enhanced to take with it:

  • the type name we want to validate the object against
  • the variable name where the object will be assigned if the type validation succeeds.

So if I had something like the below:

Object intObj = 45;
if(intObj instanceof String str){
	System.out.println(str.toUpperCase());
}

The instanceof validation would never succeed and hence no further operations. I can even add additional validations to go with the instanceof check like:

Object intObj = 45;
if(intObj instanceof String str && str.length() > 0){
	System.out.println(str.toUpperCase());
}

In the above code snippet, we are trying to convert the object to uppercase if the intObj is a String and is not empty. But the below will not even compile because it is possible that the instanceof validation will fail and the variable str will never be initialized leading to NullPointerException

Object intObj = 45;
//this will never compile
if(intObj instanceof String str || str.length() > 0){
	System.out.println(str.toUpperCase());
}

Scope of instanceof variable

Let us see with examples about the scope of the variable declared with instanceof.

The scope of the variable declared with instanceof if the validation succeeds are:

  • the statements following the instanceof check. In our above example it would be the str.lenght() > 0 expression
  • the code block associated with the if condition.

Sometimes we would have a method defined in such a way that if the instanceof fails then we return otherwise we perform the required operations. In such a scenario the scope of the instanceof variable is the rest of the method.

Let us look at the code snippet below to understand this

public static void scopeCheck(Object obj){
	if(!(obj instanceof String str)){
		//str is not available here because the instanceof failed
		//System.out.println(str.toUpperCase());
		return;
	}

	System.out.println("In Scope check");
	System.out.println(str);
}

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading