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.
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:
Where is the character at index , and 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:
- 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).
- Computational Efficiency: 31 can be calculated as , 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:Here, is a bitwise operation that shifts the bits of five positions to the left, effectively multiplying it by 32. Subtracting from this result gives .
- 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:
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
| Feature | Value | Benefit |
| Multiplier | 31 | Reduces collisions, primes perform well |
| Type | Prime Number | Helps in uniform distribution |
| Binary Computation | Faster than direct multiplication | |
| Historical Usage | Used in Lisp | Proven 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
- Why does Java's hashCode in String use 31 as a multiplier?
- Why does java.util.Arrays.sortObject use 2 kinds of sorting algorithms?
- Why does Maven warn me about encoding?
- Why does MockMvc always return empty content?
- Why does my algorithm become faster after having executed several times? Java
- Why does my Spring Boot App always shutdown immediately after starting?
- Why does my Spring Boot App always shutdown immediately after starting?
- Why does spring-boot-3 give javax.servlet.http.HttpServletRequest ClassNotFoundException

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.