Type Comparison Operator

Java provides a run-time operator instanceof to
compare a class and an instance of that class.
This operator " instanceof" compares an object to a
specified class type.
The instanceof operator is defined to know about an object's relationship
with a class. It evaluates to true, if the object or array is an instance of the specified type;
otherwise it returns false. The instanceof
operator can be used with the arrays and objects. It can't be used
with primitive data types and values. Its signature is written as:
Lets have an example :
class X {
int i, j;
}
class Y {
int i, j;
}
class Z extends X {
int k;
}
public class InstanceOfDemo {
public static void main(String args[]) {
X x = new X();
Y y = new Y();
Z z = new Z();
if(x instanceof X)
System.out.println("x is an instance of X");
X obj;
obj = z; // X reference to z
if(obj instanceof Z)
System.out.println("obj is an instance of Z");
}
}
|
.Output of the Program:
C:\nisha>javac InstanceOfDemo.java
C:\nisha>java InstanceOfDemo
x is an instance of X
obj is an instance of Z |
In this example the class "Z" extends the class "X". So the expression
" if (x instanceof X)" returns true because the object of class "X" has the reference to the object of class
"Z". On the other hand, this example will generate an error, if the expression is written as
"if (y instanceof X)" because the object "y" of class
"Y" is not an object of class "X".
Download this Program

|