Course contentsShow
← Java
Lesson 2173 of 2,87043. String Handling in DepthFree lesson

Immutability Enables Hashcode Caching

Learn that String's hashCode is computed once and cached, optimizing HashMap and HashSet performance.

Immutability Enables Hashcode Caching

What you'll learn: How String's immutability allows Java to calculate the hash code once and reuse it, dramatically speeding up hash-based collections.

The Core Idea

When you use a String as a key in a HashMap or add it to a HashSet, Java needs to compute the string's hash code to determine where it belongs in the internal data structure. Computing a hash code involves iterating through every character in the string and performing mathematical operations—potentially expensive for long strings or frequent lookups.

Here's the clever optimization: because Strings are immutable, their hash code can never change. Once computed, Java caches it in a private field inside the String object. The first call to hashCode() does the calculation and stores the result. Every subsequent call simply returns the cached value—an O(1) operation instead of O(n).

Why This Matters

Consider a HashMap with thousands of lookups per second. Without caching, every lookup would recalculate the hash code by scanning every character. With caching, the second and all future lookups are nearly instant.

Analogy: Imagine looking up a friend's phone number. Without immutability, you'd have to recalculate their number every time based on some formula. With immutability (and caching), you look it up once, write it in your contacts, and just read it from there forever after.

This optimization only works because strings can't change. If you could modify a string after creation, the cached hash code would become stale and incorrect, breaking hash-based collections entirely.

Under the Hood

Internally, String has a field like private int hash; initialized to zero. The first hashCode() call computes the value; subsequent calls detect the non-zero cached value and return it immediately.

Key Takeaway: String immutability enables transparent hash code caching, making HashMap and HashSet operations with String keys dramatically faster by avoiding redundant recalculation.