How String Hashcode value is calculated?

The String hashCode() method returns the hashcode value of this String as an Integer.

Syntax:
public int hashCode()

For Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        String str = "GFG";
        System.out.println(str);
  
        int hashCode = str.hashCode();
        System.out.println(hashCode);
    }
}

chevron_right


Output:

GFG
70472

But the question here is, how this integer value 70472 is printed. If you will try to find the hashcode value of this string again, the result would be the same. So how is this String hashcode calculated?

How is String hashcode calculated?
The hashcode value of a String is calculated with the help of a formula:

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

where:

  • s[i] represents the ith character of the string
  • ^ refers to the exponential operand
  • n represents the length of the string

Example:

In the above case, the String is “GFG”. Hence:

s[] = {'G', 'F', 'G'}
n = 3

So the hashcode value will be calculated as:

s[0]*31^(2) + s[1]*31^1 + s[0]
= G*31^2 + F*31 + G
= (as ASCII value of G = 71 and F = 70)
  71*312 + 70*31 + 71 
= 68231 + 2170 + 71
= 70472

which is the value received as the output.

Hence this is how the String hashcode value is calculated.

HashCode value of empty string?

In this case, the String is “”. Hence:

s[] = {}
n = 0

So the hashcode value will be calculated as:

s[0]*31^(0)
= 0

Hence the hashcode value of an empty string is always 0.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.