Signup/Sign In
LAST UPDATED: AUGUST 27, 2020

Java Integer hashCode() Method

The hashCode() method is a part of the Integer class of the java.lang package. It is used to return the hash code of a given input. A hashcode is defined as a unique primitive integer value that is associated with every object in Java.

This method overrides the method of Class Object.

Syntax:

public int hashCode() 

Parameter:

No parameter is passed in this method.

Returns:

The equivalent primitive integer value (hash code) associated with the Integer object.

Exceptions:

The exceptions that can be encountered during the execution of this method are:

  • InputMismatchException
  • NumberFormatException

Example 1:

Here, using the hashCode() function , a hashcode is returned by the compiler.

import java.lang.Integer;

public class StudyTonight
{  
    public static void main(String[] args)  
    {  
        
        Integer n1 = 81;
        Integer n2 = 27;
           
        int hv1 = n1.hashCode();//Returning the hash code value for the object n1
        int hv2 = n2.hashCode();//Returning the hash code value for the object n2
        System.out.println("Hash code Value : " + hv1);
        System.out.println("Hash code Value : " + hv2);  
    }  
}  


Hash code Value : 81
Hash code Value : 27

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent hash code.

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args)
      {  
        try
        {
          System.out.print("Enter input: ");  
          Scanner sc = new Scanner(System.in);         
          Integer n = sc.nextInt();  
          int hv = n.hashCode(); //Returning the hash code value for the object 
          System.out.println("Hash code Value for the given input is: " + hv);
          
        }
        catch(Exception e)
        {
          System.out.println("Invalid Input!!");
        }
      
      }  
}  


Enter input: 23
Hash code Value for the given input is: 23
******************************************
Enter input: studytonight
Invalid Input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.