Java Object hashCode Method Example

In this example, we will demonstrate the usage of java.lang.Object.hashCode() method with an example.

Object hashCode() Method

The java.lang.Object.hashCode() method returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
Read the general contract of hashCode at Object hashCode() API Doc.

Object hashCode() Method Example

The following example shows the usage of lang.Object.hashCode() method:
public class Person {
  private String firstName;
  private String lastName;

  public String getFirstName() {
  return firstName;

  public void setFirstName(String firstName) {
  this.firstName = firstName;

  public String getLastName() {
  return lastName;

  public void setLastName(String lastName) {
  this.lastName = lastName;

  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
    result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
    return result;

  public static void main(String[] args) {
     Person person = new Person();


     Person person1 = new Person();
Let us compile and run the above program, this will produce the following result −
By definition, if two objects are equal, their hashcode must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course