instanceof operator vs isInstance method in java

Java Programming Java8Object Oriented Programming

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
raja
Published on 19-Sep-2018 12:15:57
Advertisements