 Open in App
Not now

# How String Hashcode value is calculated?

• Difficulty Level : Medium
• Last Updated : 01 Apr, 2020

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*31^(n-1) + s*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*31^(2) + s*31^1 + s
= 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*31^(0)
= 0
```

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

My Personal Notes arrow_drop_up