The hashCode() method is used to obtain the hash code for a string. This method does not accept any parameters as it is a default method and it returns a hash code value.
A program that demonstrates the hashCode() method in Java is given as follows:
Example
Live Demo
import java.io.*;
public class Demo {
public static void main(String args[]) {
String str = new String("The sky is blue");
System.out.println("The string is: " + str);
System.out.println("The Hashcode for the string is: " + str.hashCode());
}
}
Output
The string is: The sky is blue
The Hashcode for the string is: -729257918
Now let us understand the above program.
The string str is defined. Then the string is printed and its HashCode is also printed using the hashCode() method. A code snippet which demonstrates this is as follows:
String str = new String("The sky is blue");
System.out.println("The string is: " + str);
System.out.println("The Hashcode for the string is: " + str.hashCode());