Let’s learn instanceof operator in java.
instanceof operator in java
instanceof operator is used to check whether the object is an instance of specified type. Type can be a class or a subclass or an interface.
instanceof operator returns either true or false. Let’s see example on instanceof operator.
public class Example { public static void main(String[] args) { Example obj = new Example(); System.out.println(obj instanceof Example); } }
Output:
true
Let’s see an example for – an object of subclass type is also a type of parent class.
class Parent { } class Child extends Parent { public static void main(String[] args) { Child c = new Child(); System.out.println(c instanceof Parent); } }
Output:
true
instanceof with null
If we compare “null” with any class or interface the result is always “false”. Let’s see an example,
class Example { public static void main(String[] args) { System.out.println(null instanceof String); } }
Output:
false
instanceof – incompatible types
To use instanceof operator there should be some relation between argument types. In the below example object ‘t’ and String has no relation.
If there is no relation then we will get compile time error “Incompatible conditional operand types Thread and String”.
class Test { public static void main(String[] args) { Thread t = new Thread(); System.out.println(t instanceof String); } }
Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Incompatible conditional operand types Thread and String at Test.main(Test.java:6)