Signup/Sign In
LAST UPDATED: SEPTEMBER 3, 2020

Java Long hashCode() Method

The hashCode() method is a part of the Long 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 Object class.

Syntax:

public int hashCode() 

Parameter:

No parameter is passed in this method.

Returns:

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

Example 1:

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

import java.lang.Long;

public class StudyTonight
{  
    public static void main(String[] args)  
    {  
        
        Long n1 = 81L;
        Long n2 = 27L;
           
        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);         
            Long n = sc.nextLong();
            //Returning the hash code value for the object   
            int hv = n.hashCode(); 
            System.out.println("Hash code Value for the given input is: " + hv);
        }
        catch(Exception e)
        {
            System.out.println("Invalid Input!!");
        }
    }  
}  


Enter input: 89
Hash code Value for the given input is: 89
***********************************************
Enter input: -552
Hash code Value for the given input is: 551
***********************************************
Enter input: 0x5334
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.