Java Equals and HashCode Interview Questions & Answers

4 avg. rating (80% score) - 1 votes

Java Equals and HashCode Interview Questions & Answers

Are you prepared in attending an interview? Then do not worry, we’ve a right answer for your job interview preparation. If you are preparing for Java Equals and HashCode job interview and don’t know how to crack interview and what level or difficulty of questions to be asked in job interviews then go through Wisdomjobs Java Equals and HashCode interview questions and answers page to crack your job interview. Equals and HashCode are the methods in Java.lang.object. Equals is used to compare two Objects. There are two ways to compare, Shallow Comparison and Deep comparison. HashCode returns the hashcode value as an integer. Below is the list of frequently asked Java Equals and HashCode interview questions and answers which gets you ready to face the interviews:

Java Equals And HashCode Interview Questions

Java Equals and HashCode Interview Questions
    1. Question 1. When You Are Writing Equals() Method, Which Other Method Or Methods You Need To Override?

      Answer :

      Hashcode is the right answer. 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.

    2. Question 2. Can Two Objects Which Are Not Equal Have The Same Hashcode?

      Answer :

      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.

    3. Question 3. How Does Get() Method Of Hashmap Works, If Two Keys Have The Same Hashcode?

      Answer :

      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.

    4. Question 4. Where Have You Written Equals() And Hashcode In Your Project?

      Answer :

      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 means he is interested in examples from your domain.

    5. Question 5. Suppose Your Class Has An Id Field, Should You Include In Equals()? Why?

      Answer :

      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 transient object until they are saved into the database.

    6. Question 6. What Happens If Equals() Is Not Consistent With Compare To() Method?

      Answer :

      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 means doesn't return zero, if equals() method returns true, it may break Set contract, which is not to avoid any duplicates.

    7. Question 7. What Happens If You Compare An Object To Null Using Equals()?

      Answer :

      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.

    8. Question 8. What Is The Difference In Using Instanceof And Getclass() Method For Checking Type Inside Equals?

      Answer :

      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.

    9. Question 9. How Do You Avoid Nullpointerexception, While Comparing Two Strings In Java?

      Answer :

      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.

    10. Question 10. What Is The Difference Between "==" And Equals() Method In Java?

      Answer :

      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.

    11. Question 11. There Are Two Objects A And B With Same Hashcode. I Am Inserting These Two Objects Inside A Hashmap. Hmap.put(a,a); Hmap.put(b,b); Where A.hashcode()==b.hashcode() Now Tell Me How Many Objects Will Be There Inside The Hashmap?

      Answer :

      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.

    12. Question 12. What Is The Use Of Hashcode In Java ?

      Answer :

      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.

    13. Question 13. Why String Is Popular Hashmap Key In Java?

      Answer :

      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.

    14. Question 14. Public Class A {
      Public Static Void Main(string Args[]){
      Final String S1="job";
      Final String S2="seeker";
      String S3=s1.concat(s2);
      String S4="jobseeker";
      System.out.println(s3==s4); // Output 1
      System.out.println(s3.hashcode()==s4.hashcode()); Output 2
      }
      }
      What Will Be The Output 1 And Output 2 ?

      Answer :

      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.

    15. Question 15. What Is The Use Of Hashcode In Objects ?

      Answer :

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

    16. Question 16. Why Is String Immutable In Java ?

      Answer :

      1. 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.

      2. To Cache its Hashcode:

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

      3. Security:

      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.

    17. Question 17. What Are The Methods Of Object Class ?

      Answer :

      • 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.

    18. Question 18. What Is Rule Regarding Overriding Equals And Hashcode Method ?

      Answer :

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

Core Java Tutorial

Java Equals And Hashcode Practice Tests

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Tutorial