In Java, the instanceof
operator is used to determine if an object is an instance of a specific class or interface. It has the following syntax:
object instanceof Class
For example:
String str = "Hello"; boolean isString = str instanceof String; // isString is true Object obj = new Object(); boolean isObject = obj instanceof String; // isObject is false
The instanceof
operator returns true
if the object is an instance of the specified class or interface, or if the object is an instance of a subclass or subinterface of the specified class or interface. It returns false
if the object is not an instance of the specified class or interface.
The instanceof
operator is often used in Java to check the type of an object before casting it to a specific type. For example:
Object obj = getObject(); if (obj instanceof String) { String str = (String) obj; // do something with str }
For more information on the instanceof
operator in Java, you can refer to the Java documentation.