Home > Java > javaTutorial > body text

instanceof operator in Java

WBOY
Release: 2023-09-01 20:01:06
forward
881 people have browsed it

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)
Copy after login

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 );
   }
}
Copy after login

Output

This will produce the following result-

true
Copy after login
Copy after login

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

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 );
   }
 }
Copy after login

Output

This will produce the following result-

true
Copy after login
Copy after login

The above is the detailed content of instanceof operator in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!