Java Character hashCode Method

JavaJavaBeginner
Practice Now

Introduction

The hashCode(char ch) method is used to return the hash code of the char value passed as the argument. It returns a unique integer value (hash code) associated with the char value passed as an argument.

Create a file

Create a new file named CharHashCodeDemo.java in the ~/project directory using the following command.

touch ~/project/CharHashCodeDemo.java

Write code to generate hash code

Open the file CharHashCodeDemo.java in your favorite text editor and write the following code.

import java.util.Scanner;

public class CharHashCodeDemo {

    public static void main(String[] args) {

        try {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a character: ");
            char ch = sc.next().charAt(0);

            int hash = Character.hashCode(ch);

            System.out.println("Hash code of character " + ch + " is: " + hash);
        }catch(Exception e) {

            System.out.println("Invalid input! Please try again...");
        }
    }
}

This code will accept a character value from the user and generate the hash code associated with that character.

Compile and run the code

Open your terminal and navigate to the ~/project directory using the following command.

cd ~/project

Compile the code using the following command.

javac CharHashCodeDemo.java

Run the code using the following command.

java CharHashCodeDemo

After running the code, you will get the following message in the terminal.

Enter a character:

Type a character value and hit the Enter key. You will get the hash code of the character in the terminal.

Summary

That's it! In this lab, you have learned how to generate unique hash code values of a given character using the hashCode(char ch) method of the Character class. You have created a Java code file that accepts a character value from the user and generates the hash code associated with that character. You have also learned how to compile and run the Java code file in the terminal of the Ubuntu system.

Other Java Tutorials you may like