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); } } |
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.
Recommended Posts:
- JavaTuples hashcode() method
- ConcurrentLinkedDeque hashCode() method in Java with Example
- Stack hashCode() method in Java with Example
- LinkedHashSet hashCode() method in Java with Example
- BigInteger hashCode() Method in Java
- TreeSet hashCode() method in Java with Example
- Writer hashCode() method in Java with Example
- DecimalStyle hashCode() method in Java with Example
- LinkedBlockingDeque hashCode() method in Java with Example
- AbstractSequentialList hashCode() method in Java with Example
- HashSet hashCode() method in Java with Example
- DecimalFormat hashCode() method in Java
- GregorianCalendar hashCode() Method in Java
- Importance of Hashcode method in Java
- equals() and hashCode() methods in Java
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.


