Java String hashCode()

A hashcode is a number (object's memory address) generated from any object, not just strings. This number is used to store/retrieve objects quickly in a hashtable.

The syntax of the string hashCode() method is:

string.hashCode()

Here, string is an object of the String class.


hashCode() Parameters

The matches() method doesn't take any parameters.


hashCode() Return Value

  • returns the hashcode, which is an int value, of the string

The hash code is computed using formula:

s[0]*31(n-1) + s[1]*31(n-2) + ... + s[n-1]

where,

  • s[0] is the first element of string s, s[1] is the second element and so on.
  • n is the length of the string

Example: Java String hashCode()

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Java Programming";
    String str3 = "";

    System.out.println(str1.hashCode()); // 2301506
    System.out.println(str2.hashCode()); // 1377009627

    // hash code of empty string is 0
    System.out.println(str3.hashCode()); // 0

  }
}

Note: For two strings to be equal, their hash code also must be equal.

Did you find this article helpful?