Tag Archives: compare sub class type

Java : Instanceof Operator


The instanceof keyword can be used to test if an object is of a specified type. To check with InstanceOf follow below Syntax:

if (objectRef instanceof type)

Points to Remember

  • Applying instanceof on a null reference variable returns false because null values do not have any reference.
  • Applying instance to check subclass ‘is a’ type of its superclass will return true.

See Also :

instanceof Operator Example

In this example, you will learn about to use of instanceof operator to check the type of predefined classes as well as user-defined classes.

Here the parent is superclass and ChildA and ChildB are subclasses of the parent class.


public class Parent {

}

public class ChildA extends Parent{
	public ChildA() {
	    super();
}}

public class ChildB extends Parent{
	public ChildB() {
	    super();
	  }
}

Here you will see, how to apply instanceof and check the type before performing any operation with objects.

import java.util.ArrayList;
import java.util.Vector;

public class InstanceOfOperatorTest {

	public static void main(String[] args) {
		String str="Saurabh";

		//To check of String class
		if(str instanceof java.lang.String)
		{
			System.out.println("It's String class");
		}

		String strNull=null;
		//to check with null value always retunn false because null values not have any reference.
		if(strNull instanceof java.lang.String)
		{
			System.out.println("It's String class");
		}

		//To check parent and Child text
		Parent p=new Parent();
		ChildA a=new ChildA();
		ChildB b=new ChildB();
		Parent pA=new ChildA();
		Parent pB=new ChildB();

	   if(p instanceof Parent)
		   System.out.println("It's Parent Class");

	   if(a instanceof ChildA)
		   System.out.println("It's ChildA Class");

	   if(b instanceof ChildB)
		   System.out.println("It's ChildB Class");

	   if(pA instanceof Parent)
		   System.out.println("ChildA is type of Parent Class");

	   if(pB instanceof Parent)
		   System.out.println("ChildB is type of Parent Class");

	   //This statement will not execute because not possible case.
	   if(p instanceof ChildA)
		   System.out.println("Parent is type of ChildA Class");

	   //To check object of Collections
	   Object object = new Vector();
	    if (object instanceof Vector)
	      System.out.println("Object was an instance of the class java.util.Vector");
	    else if (object instanceof ArrayList)
	      System.out.println("Object was an instance of the class java.util.ArrayList");
	    else
	      System.out.println("Object was an instance of the " + object.getClass());

	}

}

Output


It's String class
It's Parent Class
It's ChildA Class
It's ChildB Class
ChildA is type of Parent Class
ChildB is type of Parent Class
Object was an instance of the class java.util.Vector
Advertisements