#This operator is only used for object reference variables. This operator checks whether an object belongs to a specific type (class type or interface type). The instanceof operator is written as -
( Object reference variable ) instanceof (class/interface type)
The result will be true if the object referenced by the variable on the left side of the operator passes the IS-A check of the class/interface type on the right side. Here is an example -
Live Demonstration
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 will produce the following result-
true
This operator will still return true if the object being compared is an assignment compatible with the type on the right. Here is another example -
Live Demo p>
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 will produce the following result-
true
The above is the detailed content of instanceof operator in Java. For more information, please follow other related articles on the PHP Chinese website!