Introduction
In this lab, we will go through how to use the hashCode(long n)
method in Java Long class to return the hash code of a long value passed as argument.
In this lab, we will go through how to use the hashCode(long n)
method in Java Long class to return the hash code of a long value passed as argument.
In this step, we will take input from the user and find the hash code of the input. Replace the code in the LongHashCodeLab.java
file with the following code:
// Importing required package
import java.lang.Long;
import java.util.Scanner;
public class LongHashCodeLab {
public static void main(String[] args) {
try {
// Getting the user input
System.out.print("Enter the value: ");
Scanner sc = new Scanner(System.in);
long input = sc.nextLong();
// Getting hash code of user input
int hashcodeValue = Long.hashCode(input);
// Printing the hash code value
System.out.println("Hash Code is: " + hashcodeValue);
}
catch(Exception e) {
System.out.println("Invalid Input!!");
}
}
}
Here, we have included another package java.util.Scanner
to take user input. We have used try...catch
block to handle an exception when the user enters an invalid input i.e. something other than a long value.
Compile the LongHashCodeLab.java
file using the following command:
javac LongHashCodeLab.java
Run the following command to execute the class file.
java LongHashCodeLab
Enter a long value to calculate its hash code. This will display the hash code of the long value entered as an output.
In this lab, we have learned how to use Java Long
class' hashCode(long n)
method to calculate hash code of the long value passed as an argument. We have also learned how to take the long value as user input and calculate its hash code using this method.