Elaborate the legal operands of the instance of operator in java?

Java 8Object Oriented ProgrammingProgramming

The instanceof operator in Java is used to find whether a reference is an instance of a Type i.e. class or an interface.

Example

 Live Demo

public class InstanceOfExample {
   public static void main(String args[]) {
      String str = "hello";
      boolean bool = str instanceof String;
      System.out.println(bool);
   }
}

Output

true

Legal operands of the instanceof operator

The following are the only legal operands of the instanceof operator −

  • Left operand − It must be a reference representing an object.
  • Right operand − It must be the name of Java class or, interface.

Except these two if you use any other operands a compile time error will be generated.

public class InstanceOfExample {
   public static void main(String args[]) {
      int i =20;
      boolean bool = i instanceof String;
      System.out.println(bool);
   }
}

Compile time error

InstanceOfExample.java:4: error: unexpected type
      boolean bool = i instanceof String;
                     ^
   required: reference
   found: int
1 error
raja
Published on 08-Jul-2019 16:10:51
Advertisements