Java String hashCode() Method & Example

Java String hashCode() method returns the hash code for the String. The hashcode value is used in hashing-based collections like HashMap, HashTable etc. The hashCode() method must be overridden in every class that overrides equals() method.

Read More: Contract between hashCode() and equals() methods

1. String hashCode() Method

The String.hashCode() has been defined as:

public int hashCode() {
    // The hash or hashIsZero fields are subject to a benign data race,
    // making it crucial to ensure that any observable result of the
    // calculation in this method stays correct under any possible read of
    // these fields. Necessary restrictions to allow this to be correct
    // without explicit memory fences or similar concurrency primitives is
    // that we can ever only write to one of these two fields for a given
    // String instance, and that the computation is idempotent and derived
    // from immutable state

    int h = hash;
    if (h == 0 && !hashIsZero) {
        h = isLatin1() ? StringLatin1.hashCode(value)
                       : StringUTF16.hashCode(value);
        if (h == 0) {
            hashIsZero = true;
        } else {
            hash = h;
    return h;

The hashcode for a String object is computed as:

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

where :

  • s[i] – is the ith character of the string
  • n – is the length of the string, and
  • ^ – indicates exponentiation

The String’s hashCode() overrides the Object.hashCode() method. This method returns the hashcode as an integer value.

2. String hashCode() Example

Java program for how to calculate hashcode of string. In the given example, we are calculating the hashcode of two different strings, and both produce different hashcodes.

System.out.println( "".hashCode() );

System.out.println( "hello world".hashCode() );

Program output.


Happy Learning !!

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial