Home  >  Article  >  Java  >  instanceof operator in Java

instanceof operator in Java

WBOY
WBOYforward
2023-09-01 20:01:06885browse

instanceof operator in Java

#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 -

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 );
   }
}

Output

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 -

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 );
   }
 }

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete