hashCode() String Example

hashCode() String Example

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.

hashCode() String
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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *