Java String hashCode(): Formula, Caching & Hash Collisions

The String.hashCode() method computes and returns a signed 32-bit integer hash code representing the string's character sequence.

Deterministic Polynomial Formula & Caching: Java computes hash codes using the exact polynomial formula s[0]*31^(n-1) + ... + s[n-1]. The result is cached internally after the first computation for instant O(1) lookups. To verify value equality, see equals(). For lexicographical sorting, explore compareTo(). For measuring length, see length(), or verify empty strings with isEmpty().

1. Syntax & Method Signature 🔝

The hashCode() method is inherited from Object and overridden in java.lang.String:

 // Formal signature of String.hashCode() in java.lang.String
public int hashCode()
Signature Element Type Description & Operational Contract
Parameters None Takes zero arguments; operates on the calling string instance.
Return Value int A signed 32-bit integer (can be positive, zero, or negative).
Time Complexity O(N) first call / O(1) cached Computed once in linear time, then cached in a private field.

2. Basic Hash Code Examples 🔝

Demonstrating hash outputs across different strings, case variations, and empty strings:

String s1 = "plus2net";
String s2 = "welcome";
String s3 = "WELCOME";
String empty = "";

System.out.println("plus2net: " + s1.hashCode());  // -1850174267 (negative integer)
System.out.println("welcome:  " + s2.hashCode());  // 1233099618
System.out.println("WELCOME:  " + s3.hashCode());  // 1951082306 (case-sensitive)
System.out.println("empty:    " + empty.hashCode());  // 0 (empty string is always 0)

Terminal Output:

plus2net: -1850174267
welcome:  1233099618
WELCOME:  1951082306
empty:    0

3. The Mathematical Formula and Why 31 is Used 🔝

Java defines the string hash code using a deterministic polynomial equation:

Polynomial Formula: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

In this formula, s[i] represents the character value at index i obtained via charAt(i), and n represents length(). Java uses the prime number 31 because:

  • Prime Distribution: Multiplication by a prime reduces clustering and collisions in hash table buckets.
  • CPU Optimization: Modern hardware compiles 31 * i as a single bit-shift instruction: (i << 5) - i.

We can verify this formula by calculating it manually with a for loop:

 // Replicating Java's exact formula: h = 31 * h + s.charAt(i)
String word = "Hi";
int h = 0;
for (int i = 0; i < word.length(); i++) {
    h = 31 * h + word.charAt(i);
}

System.out.println("Calculated hash: " + h);                // 2337
System.out.println("Built-in hash:   " + word.hashCode());  // 2337 ('H' * 31 + 'i' = 72 * 31 + 105 = 2337)

Terminal Output:

Calculated hash: 2337
Built-in hash:   2337

4. The equals() and hashCode() Contract 🔝

Java enforces a strict contract between equals() and hashCode():

Contract Rule Requirement Implication for Developers
s1.equals(s2) == true Mandatory Hash codes must be identical: s1.hashCode() == s2.hashCode().
s1.hashCode() == s2.hashCode() Optional Strings might be equal, or might be a hash collision.
String strA = new String("Java");
String strB = new String("Java");

 // 1. Equal strings MUST have identical hash codes
System.out.println("strA.equals(strB):     " + strA.equals(strB));          // true
System.out.println("strA.hashCode():        " + strA.hashCode());           // 2301506
System.out.println("strB.hashCode():        " + strB.hashCode());           // 2301506
System.out.println("Same hash code?         " + (strA.hashCode() == strB.hashCode()));  // true

Terminal Output:

strA.equals(strB):     true
strA.hashCode():        2301506
strB.hashCode():        2301506
Same hash code?         true

5. Understanding Hash Collisions in Java 🔝

Because there are infinite possible strings but only 2^32 distinct 32-bit integers, different strings will occasionally share the exact same hash code. This is called a hash collision:

 // Famous Java String hash collisions
String pair1A = "FB";
String pair1B = "Ea";

System.out.println("pair1A hash: " + pair1A.hashCode());  // 2236
System.out.println("pair1B hash: " + pair1B.hashCode());  // 2236
System.out.println("Are strings equal? " + pair1A.equals(pair1B));  // false!

String pair2A = "Aa";
String pair2B = "BB";
System.out.println("pair2A hash: " + pair2A.hashCode());  // 2112
System.out.println("pair2B hash: " + pair2B.hashCode());  // 2112

Terminal Output:

pair1A hash: 2236
pair1B hash: 2236
Are strings equal? false
pair2A hash: 2112
pair2B hash: 2112

6. Production Recipe: Safe HashMap Bucket Indexing 🔝

Because hash codes can be negative, taking a simple modulo hash % count can produce invalid negative indices. Masking with 0x7FFFFFFF clears the sign bit:

public class HashBucketMapper {
    public static int getBucketIndex(String key, int bucketCount) {
        if (key == null) return 0;
         // Mask with 0x7FFFFFFF to convert negative hashes to non-negative integers
        int nonNegativeHash = key.hashCode() & 0x7FFFFFFF;
        return nonNegativeHash % bucketCount;
    }

    public static void main(String[] args) {
        int buckets = 16;
        System.out.println("Bucket for 'alpha':    " + getBucketIndex("alpha", buckets));
        System.out.println("Bucket for 'plus2net': " + getBucketIndex("plus2net", buckets));
    }
}

Terminal Output:

Bucket for 'alpha':    14
Bucket for 'plus2net': 11

7. Immutability and Internal Hash Code Caching 🔝

Because strings are immutable, the hash code can never change after initialization. Java stores the value in a private field hash so subsequent calls return immediately:

String article = "Modern Java tutorial for enterprise architectures";

 // First call: scans string and caches result in internal private 'hash' field in O(N) time
long t0 = System.nanoTime();
int h1 = article.hashCode();
long elapsed1 = System.nanoTime() - t0;

 // Second call: directly returns cached value in O(1) time
long t1 = System.nanoTime();
int h2 = article.hashCode();
long elapsed2 = System.nanoTime() - t1;

System.out.println("Hash code: " + h1);
System.out.println("Second call executed instantly via cached field.");

Terminal Output:

Hash code: 2026118491
Second call executed instantly via cached field.

8. Common Developer Pitfalls & Traps 🔝

Assuming Unique Hashes for Cryptography

String.hashCode() is designed for hash tables, not cryptographic security. Do not use it for password hashing or checksums. For secure digests, use SHA-256 via getBytes().

The Math.abs(Integer.MIN_VALUE) Trap

Calling Math.abs(str.hashCode()) to make a hash positive fails if the hash equals Integer.MIN_VALUE (-2147483648), because Math.abs(Integer.MIN_VALUE) returns negative! Always mask with hash & 0x7FFFFFFF.

9. Complete Compilable Java Program 🔝

You can compile and run this complete verification class locally in any Java IDE or environment:

public class StringHashCodeFullDemo {
    public static void main(String[] args) {
        String test = "plus2net";

         // 1. Verify predictable hash calculation
        if (test.hashCode() == -1850174267) {
            System.out.println("Check 1 Passed: Known string hash code verified.");
        }

         // 2. Verify empty string has hash 0
        if ("".hashCode() == 0) {
            System.out.println("Check 2 Passed: Empty string hash code is exactly 0.");
        }

         // 3. Verify collision handling
        if ("FB".hashCode() == "Ea".hashCode() && !"FB".equals("Ea")) {
            System.out.println("Check 3 Passed: Hash collision detected and verified.");
        }

        System.out.println("All String.hashCode() verification checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: Known string hash code verified.
Check 2 Passed: Empty string hash code is exactly 0.
Check 3 Passed: Hash collision detected and verified.
All String.hashCode() verification checks passed successfully!

10. Frequently Asked Questions (FAQ) 🔝

Can String.hashCode() return a negative number?

Yes. Java integers are signed 32-bit values. Arithmetic overflow during polynomial multiplication frequently produces negative results.

What is the hash code of an empty string?

The hash code of "" is always 0, as specified in the Java language specification.

Are hash codes consistent across different JVM executions?

Yes. Because the polynomial formula is explicitly defined in the Java specification, a given string will produce the identical hash code on any compliant JVM.

Does String.hashCode() throw NullPointerException on null?

Yes. Calling null.hashCode() crashes with a NullPointerException. Check that the reference is non-null before invoking.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer