java instanceof

java

In Java, the instanceof operator is used to determine if an object is an instance of a particular class or implements a particular interface. It has the following syntax:

object instanceof class

The instanceof operator returns true if the object is an instance of the specified class or implements the specified interface, and false otherwise.

Here is an example of how you can use the instanceof operator in Java:

public class Main {
  public static void main(String[] args) {
    Object obj = "hello";

    if (obj instanceof String) {
      String str = (String) obj;
      System.out.println(str);
    }
  }
}

In this example, we create an object of type Object and assign it a string value. We then use the instanceof operator to check if the object is an instance of the String class, and if it is, we cast the object to a String and print it to the console.

Note: The instanceof operator is often used in Java to check the type of an object before performing a specific action on it. It is particularly useful when working with polymorphic objects, where an object can have multiple types due to inheritance or interface implementation.