The instanceof operator in Java

The instanceof operator in Java


Posted in : Core Java Posted on : October 13, 2010 at 6:36 PM Comments : [ 0 ]

This section contains the detail about the instanceof operator in Java

The instanceof operator in Java

This operator is used only for checking "object reference variables". This operator checks the type of "object reference variable " and return "true" if it is of the provided type.

if (objectReference instanceof type)

In this syntax, "objectReference" is the object name and "type" is the name of object type for checking it's type. The operator checks whether the object is of a particular type(class type or interface type). For example :

Car c = new Car();
boolean result = c instanceof Car;

This will return 'true' and store 'true' to boolean variable 'result'

Example :


class A1 {
	int i, j;
}

class B1 {
	int i, j;
}

class C1 extends A1 {
	int k;
}

class D1 extends A1 {
	int k;
}

class InstanceOfDemo {
  public static void main(String args[]) {
	A1 a = new A1();
	B1 b = new B1();
	C1 c = new C1();
	D1 d = new D1();
	
	if (a instanceof A1)
		System.out.println("a is instance of A");
	if (b instanceof B1)
		System.out.println("b is instance of B");
	if (c instanceof C1)
		System.out.println("c is instance of C");
	if (c instanceof A1)
		System.out.println("c can be cast to A");
	
	if (a instanceof C1)
		System.out.println("a can be cast to C");
	
	System.out.println();
	
	A1 ob;
	
	ob = d; // A reference to d
	System.out.println("ob now refers to d");
	if (ob instanceof D1)
		System.out.println("ob is instance of D");
	
	System.out.println();
	
	ob = c; // A reference to c
	System.out.println("ob now refers to c");
	
	if (ob instanceof D1)
		System.out.println("ob can be cast to D1");
	else
		System.out.println("ob cannot be cast to D1");
	
	if (ob instanceof A1)
		System.out.println("ob can be cast to A1");
	
	System.out.println();
	
	// all objects can be cast to Object
	if (a instanceof Object)
		System.out.println("a may be cast to Object");
	if (b instanceof Object)
		System.out.println("b may be cast to Object");
	if (c instanceof Object)
		System.out.println("c may be cast to Object");
	if (d instanceof Object)
		System.out.println("d may be cast to Object");
	}
}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac InstanceOfDemo.java

C:\Program Files\Java\jdk1.6.0_18\bin>java InstanceOfDemo
a is instance of A
b is instance of B
c is instance of C
c can be cast to A

ob now refers to d
ob is instance of D

ob now refers to c
ob cannot be cast to D1
ob can be cast to A1

a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics