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. 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 firstname.lastname@example.org. 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.
- How to make object eligible for garbage collection in Java?
- Different ways of Reading a text file in Java
- Java.io.File Class in Java
- Iterators in Java
- new operator vs newInstance() method in Java
- Mark-and-Sweep: Garbage Collection Algorithm
- Comparable vs Comparator in Java
- Reflection in Java
- Iterator vs Foreach In Java
- Collections in Java
- Generics in Java
- Garbage Collection in Java
- Redirecting System.out.println() output to a file in Java
- Serialization and Deserialization in Java with Example
- String vs StringBuilder vs StringBuffer in Java