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
- TreeSet hashCode() method in Java with Example
- Map hashCode() Method in Java with Examples
- BigDecimal hashCode() Method in Java
- Set hashCode() method in Java with Examples
- ConcurrentLinkedDeque hashCode() method in Java with Example
- Vector hashCode() Method in Java
- LinkedHashSet hashCode() method in Java with Example
- Stack hashCode() method in Java with Example
- GregorianCalendar hashCode() Method in Java
- IdentityHashMap hashCode() Method in Java
- DecimalStyle hashCode() method in Java with Example
- BigInteger hashCode() Method in Java
- OffsetTime hashCode() in Java with examples
- AbstractSequentialList hashCode() method in Java with Example
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.



