instanceof operator vs isInstance() Method in Java – GeeksforGeeks

The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.

The 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 the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.

The instanceof operator and isInstance() method both return a boolean value. isInstance() method is a method of class Class in java while instanceof is an operator. 

Consider an Example:

Tóm Tắt

Java




  

public class Test

{

    public static void main(String[] args)

    {

        Integer i = new Integer(5);

  

        

        

        System.out.println(i instanceof Integer);

    }

}



Output: 

true

Now if we want to check the class of the object at run time, then we must use isInstance() method.

Java




public class Test {

    

    

    

    public static boolean fun(Object obj, String c)

        throws ClassNotFoundException

    {

        return Class.forName(c).isInstance(obj);

    }

  

    

    public static void main(String[] args)

        throws ClassNotFoundException

    {

        Integer i = new Integer(5);

  

        

        

        boolean b = fun(i, "java.lang.Integer");

  

        

        

        boolean b1 = fun(i, "java.lang.String");

  

        

        

        

        boolean b2 = fun(i, "java.lang.Number");

  

        System.out.println(b);

        System.out.println(b1);

        System.out.println(b2);

    }

}



Output: 

true
false
true

Note: instanceof operator throws compile-time error(Incompatible conditional operand types) if we check object with other classes which it doesn’t instantiate.

Java




public class Test {

    public static void main(String[] args)

    {

        Integer i = new Integer(5);

  

        

        

        

        System.out.println(i instanceof String);

    }

}



Output : 

9: error: incompatible types: Integer cannot be converted to String
        System.out.println(i instanceof String);
                           ^

Must Read:

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes

arrow_drop_up