Looking at Java's String class we can see that hash code is cached after first evaluation.
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
Where hash is an instance variable. I have a question, why do we need that h extra variable?
Stringclass is thread-safe. You can read more about this concept here