What is a hash code in Java?

A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap.

The hashCode() method

In Java, the hash code value of an object is returned by calling the hashCode() method, on that object. This method is implemented, by default, in the Object class and is, therefore, inherited by user-defined classes as well.

This method returns the same integer value (when called on the same object during the same instance of a Java application), provided that no data used by the equals() method is modified.

When hashCode() is called on two separate objects (which are equal according to the equals() method) it returns the same hash code value. However, if it is called on two unequal objects, it will not necessarily return different integer values.