Monday, October 3, 2022

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:

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);
    }
}
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[2]
= 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.

No comments:

Post a Comment

techguruspeaks

  Core Java programming Introduction to Java Java Features Writing a Simple Java Program Java Keywords and Comments Variables, Identifiers &...