Top 18 Java Equals And Hashcode Interview Questions You Must Prepare 14.Jun.2024

@String Pool:

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

@To Cache its Hashcode:

If string is not immutable, One can change its hashcode and hence not fit to be cached.


String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

This is an interesting questions, which asked along with equals() and hashCode() contract. Some java.util.Set implementation e.g. SortedSet or it's concrete implementation TreeSet uses compareTo() method for comparing objects. If compareTo() is not consistent me doesn't return zero, if equals() method returns true, it may break Set contract, which is not to avoid any duplicates.

This is the follow-up of previous interview questions on equals and hashcode, in fact, sometimes this leads to a discussion of the earlier point. When two key return same hashcode, they end up in the same bucket. Now, in order to find the correct value, you used keys.equals() method to compare with key stored in each Entry of linked list there. Remember to point out keys.equals() method, because that's what interviewer is looking for.

When a null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). By the way, if you comparing String literal with another String object then you better call equals() method on the String literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java.

This question is asked to one of my readers as Hibernate Interview question, well including id is not a good idea in equals() method because this method should check equality based upon content and business rules. Also including id, which is mostly a database identifier and not available to trient object until they are saved into the database.

A Class must override the hashCode method if its overriding the equals method.

Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.

Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.

YES, two objects, which are not equal to equals() method can still return same hashCode. By the way, this is one of the confusing bit of equals and hashcode contract. See Core Java, Volume 1 9th Edition by Cay S. Horstmann for  more details.

One of the most classic interview question on equals(). It has been asked numerous times during in past decade. I have also covered this question already. See here for a detailed discussion on how it affect equality checking of String and Integer in the autoboxing world.

equals vs == in Java

That's all on this list of Java interview Questions on Equals and HashCode methods in Java. It's one of the fundamental concepts of Java programming language, but yet has several subtle things, which is unknown to many Java programmers. I strongly suggest to get yourself really good on equals(), hashCode(), compareTo() and compare() method, not only to do well on Java Interviews but also to write correct code in Java.

There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.

  • clone() - Creates and returns a copy of this object.
  • equals() - Indicates whether some other object is "equal to" this one.
  • finalize()  - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
  • getClass() - Returns the runtime class of an object.
  • hashCode() - Returns a hash code value for the object.
  • toString() - Returns a string representation of the object.
  • notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program.

This question was asked multiple times, sometimes by looking at your equals() and hashCode implementation. Well, key difference comes from the point that instanceof operator returns true, even if compared with subclass e.g. Subclass instanceof Superclass is true, but with getClass() it's false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with subclass object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a.equals(b) is true than b.equals(a) should also be true. Just replace a and b with an instance of Superclass and Subclass, and you will end up breaking symmetry rule for equals() method.

Since when compared to null, equals return false and doesn't throw NullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String variable str, then you should call equals as "abc".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. On the other hand, if you call str.equals("abc"), it will throw NPE. So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals() method.

Hashcode is the right wer. Since equals and hashCode have their contract, so overriding one and not other will break the contract between them. By the way this question can lead to an interesting discussion, if Interviewer likes to go on deep e.g. he may ask what are those contracts, what happens if those contracts break etc. I like to give an example How equals and hashcode are used in hash based collections e.g. Hashtable, that leaves positive impression more often. You can also mention about compareTo() here to score some additional point, this method should also need to be consistent with equals, which is another interesting question on our list.

This is to see if the developer has even written these methods or not. Of course, almost all of Java programmer are exposed to this, you can point out value objects, Hibernate entities from your domain, where you have overridden equals and hashCode. Always gives examples from your domain and from your project, rather than a trivial example from a test program, because if Interviewer is asking this question, it me he is interested in examples from your domain.