0% found this document useful (0 votes)
21 views

Instanceof Operator

The instanceof operator checks if an object is of a specific type and returns true if it passes the "IS-A" check against the type. It can be used to check both class and interface types, and will return true if the object is assignment compatible with the type even if it is not an exact match but is a subclass or subinterface. Examples are provided demonstrating checking a String object's type and a Car object's type even when it is referenced by a parent Vehicle class variable.

Uploaded by

crazz1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Instanceof Operator

The instanceof operator checks if an object is of a specific type and returns true if it passes the "IS-A" check against the type. It can be used to check both class and interface types, and will return true if the object is assignment compatible with the type even if it is not an exact match but is a subclass or subinterface. Examples are provided demonstrating checking a String object's type and a Car object's type even when it is referenced by a parent Vehicle class variable.

Uploaded by

crazz1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

instanceof Operator:

This operator is used only for object reference variables. The


operator checks whether
the object is of a particular type(class type or interface type).
instanceof operator is
wriiten as:
( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the


operator passes the IS-A
check for the class/interface type on the right side, then the
result will be true.
Following is the example:
public class Test {
public static void main(String args[]){
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}

This would produce the following result:


true

This operator will still return true if the object being compared
is the assignment
compatible with the type on the right. Following is one more
example:
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}

This would produce the following result:


true

You might also like