The Java programming language and JVM are full of hidden gems and even though I am using Java for more than a decade I still get surprised by features that I didn't know for quite some time like shutdown hook, covariant method overriding, and JVM option to refresh DNS cache. The instanceof operator is also one of the rarely known features of Java, It is used to check if an object is the instance of a particular class or not. It returns true if the object is an instance of the class, otherwise, returns false. You might have seen usages of the instanceof keyword in Java while overriding the equals() method. Since for checking equality of two instances, the first step is to verify whether they are the instance of the same object or not, you can use the instanceof operator there.
Some of you might have used the Class.getClass() method there but there is a slight difference between using instanceof and using getClass() while overriding equals in Java, which is also one of the tricky questions from Java Interviews.
The instanceof operator will return true even if the object is an instance of subclass but getClass() will only return true if an object is indeed an instance of the specified class, in the case of subclass it would just return false.
This property can work in your favor just like it does for Hibernate, which replaces your classes with Proxies, but it can also break equals() symmetry contract.
In this article, we will see an example of the instanceof operator and learn some important points about it, so that you can not only learn how to use instanceof operator but also understand when to use the instanceof operator in Java.
Some of you might have used the Class.getClass() method there but there is a slight difference between using instanceof and using getClass() while overriding equals in Java, which is also one of the tricky questions from Java Interviews.
The instanceof operator will return true even if the object is an instance of subclass but getClass() will only return true if an object is indeed an instance of the specified class, in the case of subclass it would just return false.
This property can work in your favor just like it does for Hibernate, which replaces your classes with Proxies, but it can also break equals() symmetry contract.
In this article, we will see an example of the instanceof operator and learn some important points about it, so that you can not only learn how to use instanceof operator but also understand when to use the instanceof operator in Java.
By the way, if you are new to Java programming then also suggest you join a comprehensive online course like The Complete Java Masterclass to learn Java in a more structured way. This course is one of the most up-to-date and comprehensive with 80+ hours of content and you can buy in just $10 on Udemy sales.
What is instanceof operator in Java with Example
As I told you, the instanceof keyword represents a binary operator which is used to check if an object is really an instance of a specified class or not. It returns true if an object is the instance of a specified object or instance of subclass or sub-interface of the specified object, otherwise, it returns false.Let's see a couple of more examples and key points about the instanceof operator in Java.
1. instanceof keyword example in Java
The syntax of the instanceof operator is following:
if(anObject instanceof aClass){ aClass cls = (aClass) anObject; }where anObject is the instance and aClass is the class or interface like Runnable, String, Number, etc, a more familiar instanceof example could be like this:
if(aThread instanceof Runnable){ Runnable r = (Runnable) aThread; }If you want to learn more about instanceof operator in Java, I suggest reading a core Java book or joining a course like Core Java Made Easy (Covers the latest Java 15) on Udemy.
If the reference variable is null then also instanceof the operator doesn't throw NullPointerException, instead, it just returns false, Even if you test with the null literal it will work fine.
if (null instanceOf Runnable){ // do something }This code will not throw NullPointerExcepiton but the code inside if block will not get executed because the instanceof will return false. that's why it's often used to prevent NullPointerException in Java, one of the techniques to avoid NullPointerException.
3. How to prevent ClassCastException using instanceof in Java
The instanceof operator is often used to prevent ClassCastExeption as well. If you remember, casting one object into another can result in ClassCastException if they are of a different type, but you can prevent that by using instanceof operator before casting, as shown in the following example:
If an object passes the instanceof check then it can be safely cast into the corresponding object, see how type casting works in Java for more details. It can also be used if an object belongs to a parent class in complex hierarchies like the Collection framework or family tree.
if(anObject instanceof aClass){ aClass cls = (aClass) anObject; }
If an object passes the instanceof check then it can be safely cast into the corresponding object, see how type casting works in Java for more details. It can also be used if an object belongs to a parent class in complex hierarchies like the Collection framework or family tree.
4. Runtime Type Identification
The instanceof operator can use to implement RTTI (runtime type identification) in Java. It returns true if the object is really an instance of the class or its subclass or subinterface as shown in the following example
Thread t = new Thread(); boolean result = false; // true because t is instance of Thread which is subclass of Object result = t instanceof Object; // true because t is object of Thread which implements Runnable interface result = t instanceof Runnable; // true bease t is an instance of Thread class result = t instanceof Thread; // false because Thread doesn't implement Callable result = t instanceof Callable; // false because t is null; t = null; result = t instanceof Thread;
5. Use of instanceof in Hibernate
Similar to transient and volatile, the instanceof keyword is also a lesser understood keyword in Java. The instanceof operator owes its recent awareness to Hibernate, a popular object-relational mapping (ORM) framework in Java that leverages the capability of this operator to implement proxies in Hibernate.
That's all about instanceof operators in Java. It's one of the fundamental operators in Java which you can use to check the type of an object at runtime. You can also prevent NullPointerExeption and ClassCastException by using this operator.
That's all about instanceof operators in Java. It's one of the fundamental operators in Java which you can use to check the type of an object at runtime. You can also prevent NullPointerExeption and ClassCastException by using this operator.
The most common use of instanceof operator is in equals() method, which is also a requirement for Hibernate entity classes because when you use the instnaceof then subclasses can also be equal o superclass objects.
Other Core Java tutorials on Operators you may like:
- How to use the Modulo or Remainder operator in Java? (example)
- How to sort HashMap in Java by keys (example)
- How to use bitwise AND, OR, and NOT operator in Java? (example)
- Difference between == and equals() in Java? (answer)
- Java Interview questions on basic operators? (questions)
- Difference between String literal and new String() object? (answer)
- How to get key from HashMap by passing values (example)
- 10 Example of Concurrent HashMap in Java (examples)
- Difference between bitwise and logical AND, OR operator in Java? (answer)
- 21 HashMap Interview questions for Java Programmers (questions)
- Difference between bitwise and bit shift operators in Java? (answer)
- 5 Best Courses to learn Java Collection Framework (courses)
- 2 ways to sort HashMap in Java? (examples)
- How to sort HashMap by values in Java 8? (example)
- Difference between HashMap, LinkedHashMap, and TreeMap in Java (answer)
Thanks for reading this Java tutorial so far. If you like this instanceof tutorial for Java beginners then please share it with your friends and colleagues. If you have any question or feedback
then please drop a comment
P. S. -
If you are new to Java programming and looking for a free online course to learn Java in-depth then I highly recommend you to check out this Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1 million students have already joined this course and you can join too to start learning Java today.
are u there?
ReplyDeleteyes
ReplyDelete