Signup/Sign In

Java Character hashCode() Method

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

Syntax:

public int hashCode() 

Parameter:

No parameter is passed in this method.

Returns:

It returns an equivalent primitive integer value (hash code) associated with the Character object.

Example 1:

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

import java.lang.Character;
public class StudyTonight 
{
	public static void main(String[] args) 
	{
		Character ch1 = 'M';
		Character ch2 = 'v';

		int hv1 = ch1.hashCode(); //Returning the hash code value for the object ch1
		int hv2 = ch2.hashCode(); //Returning the hash code value for the object ch2
		System.out.println("Hash code Value : " + hv1);
		System.out.println("Hash code Value : " + hv2);
	}
}


Hash code Value : 77
Hash code Value : 118

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 );
			Character ch = sc.next().charAt(0);
			int hv = ch.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: h
Hash code Value for the given input is: 104
****************************************************
Enter input: T
Hash code Value for the given input is: 84

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.