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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Class isInstance() method in Java with Examples
- Java instanceof and its applications
- Using throw, catch and instanceof to handle Exceptions in Java
- new operator vs newInstance() method in Java
- new operator in Java
- Java Ternary Operator Puzzle
- Double colon (::) operator in Java
- Difference between concat() and + operator in Java
- && operator in Java with Examples
- & Operator in Java with Examples
- Equality (==) operator in Java with Examples
- Java Unary Operator with Examples
- Java Ternary Operator with Examples
- Java Assignment Operator with Examples
- Diamond operator for Anonymous Inner Class with Examples in Java
- || operator in Java
- Java Program To Find Largest Between Three Numbers Using Ternary Operator
- Multiples of 3 and 5 without using % operator
- Java.util.Collections.rotate() Method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
Improved By : _tanyajain