Java
hashCode()
Programming
String Manipulation
Software Development

Why does Java's hashCode() in String use 31 as a multiplier?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In many programming languages, hashing is a common technique used to optimize data retrieval times. Hash functions are crucial for efficient data storage and retrieval in data structures such as hash tables or hash sets. Java’s String class has its own implementation of the hashCode() method, which uses the number 31 as a multiplier. This choice, while seemingly arbitrary, is deeply rooted in the considerations of simplicity, performance, and historical usage.

Understanding the hashCode() Implementation

Java’s String.hashCode() method calculates the hash code using a formula where each character of the string contributes to the final hash value. According to the Java documentation, the hash code for a String object is computed as:

s[0]×31(n1)+s[1]×31(n2)+...+s[n1]s[0] \times 31^{(n-1)} + s[1] \times 31^{(n-2)} + ... + s[n-1]

Where s[i]s[i] is the character at index ii, and nn is the length of the string. The value 31 is used as the multiplier for each character in the string.

Why Choose 31?

The choice of the number 31 as a multiplier in the hash function is not accidental but intentioned for several reasons:

  1. Prime Number: 31 is a prime number. Using a prime number as a multiplier can help in a more uniform distribution of hash codes, as it decreases the number of collisions in the hash table (where different strings have the same hash code).
  2. Computational Efficiency: 31 can be calculated as 2512^5 - 1, which allows for some optimizations at the binary level. In particular, multiplication by 31 can be replaced by a bitwise shift and subtraction, which is faster than direct multiplication:
    31×i=(i<<5)i31 \times i = (i << 5) - i
    Here, i<<5i << 5 is a bitwise operation that shifts the bits of ii five positions to the left, effectively multiplying it by 32. Subtracting ii from this result gives 32ii=31i32i - i = 31i.
  3. Historical Reason: The number 31 was historically used by the hashing algorithm in Lisp programming language and was arguably adopted by other languages due to its success in distributing hash values uniformly.

Examples of Hash Code Calculation

Consider a string "ab". According to the formula, the hash code would be computed as:

hash=a×311+b×310=97×31+98=3107hash = 'a' \times 31^1 + 'b' \times 31^0 = 97 \times 31 + 98 = 3107

Performance Implications

The choice of hash function impacts the performance of storing and retrieving items from a hash-based data structure. By using 31, Java’s String.hashCode() is not only efficient in computation but also effective in reducing hash collisions. A good hash function should distribute hash values uniformly even if the inputs have common patterns. For strings, where certain patterns and groupings of characters can be more frequent, a careful choice of multiplier helps maintain balanced performance.

Summary Table

FeatureValueBenefit
Multiplier31Reduces collisions, primes perform well
TypePrime NumberHelps in uniform distribution
Binary Computation31×i=(i<<5)i31 \times i = (i << 5) - iFaster than direct multiplication
Historical UsageUsed in LispProven effectiveness in hash functions

Conclusion

The use of the number 31 in Java’s hashCode() method for strings exemplifies a well-balanced trade-off between computational efficiency and a low rate of hash collisions. This deliberate choice helps in optimizing the performance of Java applications that rely heavily on hash tables, especially when handling large volumes of data. Understanding such intricacies not only aids in appreciating Java’s internal workings but also serves as a lesson in the subtle art of programming language design.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions