Java Tutorial Java Advanced Java References

Java String - hashCode() Method



The Java hashCode() method returns a hash code for the given string. The hash code of a given string is calculated as:

hashcode

where s[ i ] is the ith character in the string and n is the length of the string.

Syntax

public int hashCode()

Parameters

No parameter is required.

Return Value

Returns a hash code for the given string.

Exception

NA.

Example:

In the example below, hashCode() method returns a hash code for the given string. It is further used to compare strings.

public class MyClass {
  public static void main(String[] args) {
    //creating strings
    String str1 = "Hello";
    String str2 = "Hello";
    String str3 = "World";

    //printing the strings
    System.out.println(str1.hashCode());
    System.out.println(str2.hashCode());
    System.out.println(str3.hashCode());

    System.out.println();
    //comparing hasCodes of str1 and str2 to check equality
    if(str1.hashCode() == str2.hashCode())
      System.out.println("str1 and str2 are equal.");
    else
      System.out.println("str1 and str2 are not equal.");

    //comparing hasCodes of str1 and str3 to check equality
    if(str1.hashCode() == str3.hashCode())
      System.out.println("str1 and str3 are equal.");
    else
      System.out.println("str1 and str3 are not equal.");
  }
}

The output of the above code will be:

69609650
69609650
83766130

str1 and str2 are equal.
str1 and str3 are not equal.

❮ Java String Methods