instanceof operator vs isInstance method in java


isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if type is to be checked at runtime then use isInstance method otherwise instanceof operator can be used. See the example below −

Example

 Live Demo

public class Tester{
   public static void main(String[] args) throws ClassNotFoundException {
      Integer i = new Integer(10);
      System.out.println(usingInstanceOf(i));
      System.out.println(usingIsInstance(i));
   }

   public static String usingInstanceOf(Object i){
      if(i instanceof String){
         return "String";
      }
      if(i instanceof Integer){
         return "Integer";
      }
      return null;
   }
   public static String usingIsInstance(Object i) throws ClassNotFoundException{
      if(Class.forName("java.lang.String").isInstance(i)){
         return "String";
      }
      if(Class.forName("java.lang.Integer").isInstance(i)){
         return "Integer";
      }
      return null;
   }
}

Output

Integer
Integer

Updated on: 23-Jun-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements