instanceof operator and isInstance() method both are used for checking the class of the object. But main difference comes when we want to check the class of object dynamically. In this case isInstance() method will work. There is no way we can do this by instanceof operator.
instanceof operator and isInstance() method both return a boolean value. isInstance() method is a method of class Class in java while instanceof is a operator.
Consider an example:
Now if we want to check the class of the object at run time, then we must use isInstance() method.
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.
13: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.