This post is part of series on little known features of java. Earlier posts covered instances accessing private members from same class, usage of class sun.misc.Unsafe and checked exception thrown through constructors for initializer blocks. In this post, I am discussing about a very common practice adopted by beginner level developers when using instanceof operator.

How many times, you have come across this type of code:

	if(list != null && list instanceof ArrayList)              //Null check not needed
	{
		//Some application logic
	}

Well, the point is that you do not need to make explicit null check here. instanceof operator does it internally for you. So below code is valid example:

package com.howtodoinjava.demo;

import java.util.ArrayList;
import java.util.List;

public class InstanceOfTest
{
	static List<String> list = null;
	
	public static void main(String[] args) {
		
		if(list instanceof ArrayList){                     //Correct way
			System.out.println("In if block");
		}
		else
		{
			System.out.println("In else block");
		}
	}
}

Output:

In else block

Logical reasoning


As per jls specification, at run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

It also say in first line that “The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.”

It means java has something called null type also, and this null type is checked in instanceof operator which obviously returns false because it is expecting ArrayList type.

Guys, I really welcome you all if you can make out any good reason with above two statements.

Happy Learning !!