java.lang.String class comes with many methods towards increasing performance. Think of comparing two strings for their equality, each having 1000 characters. Comparing each character in a for loop is a time cosuming process where performance is lost. Java comes with an idea. Each string is converted into an integer value (following some formula) and then compared. Each string with different characters will have different integer values. The integer value is hash code. Now read further hashCode() String.
The integer value of string representation is known as hash code and the process of conversion is known as hashing. Two strings having same characteres in the same sequence will have same hash code value. To convert a string into hash code, String class comes with hashCode() method. The hash code of an empty string is 0.
The signature is given as defined in String class
- public int hashCode(): Returns the hash code of the string. Hash code is returned as an int value.
Following example on hashCode() String illustrates the method.
public class StringMethodDemo
public static void main(String args)
String str1 = ""; // empty string
String str2 = "hello";
String str3 = "hello";
String str4 = "Hello";
String str5 = str4;
System.out.println("Hash code of empty string: " + str1.hashCode());
System.out.println("Hash code of " + str2 + ": " + str2.hashCode());
System.out.println("Hash code of " + str3 +": " + str3.hashCode());
System.out.println("Hash code of " + str4 + ": " + str4.hashCode());
System.out.println("Hash code of " + str5 + ": " + str5.hashCode());
System.out.println("\nHash code of Aa: " + "Aa".hashCode());
System.out.println("Hash code of BB: " + "BB".hashCode());
Observe the hash codes of different strings in this hashCode() String Example
String str5 = str4;
When assigned, string str5 refers str4, their hash codes are same.
Hash code does case-sensitive conversion. That is, strings "hello" and "Hello" will have different hash codes.
Hash codes are used internally by Java to compare strings or data structures as follows.
if(str1.hashCode() == str2.hashCode())
System.out.println("Strings are same");
Hashing is used to store elements in HashMap and HashSet.
Precaution with Hash code
If two strings with different characters have the same hash code, it is called collision. Collisions are very rare and may be one or two in lakhs. But chance is a chance. The hash code of "Aa" and "BB" is same of 2112. See the output screen.
Learn more on hash code at Object comparison – hashCode() & equals().
Would you like to know Differences hashcode() vs equals() in Java.