Java String hashCode() Method

Intermediate
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, hashCode() returns an int computed from the characters of the string. The formula is fixed by the specification: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], using int arithmetic, and the empty string hashes to 0.

Because the formula depends only on the characters, two strings that are equals always have the same hash code, which is what HashMap and HashSet rely on. The value is the same on every JVM, so "hello".hashCode() is always 99162322.

hashCode() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.hashCode(); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.

Syntax

Call it with no arguments; collections call it for you when strings are used as keys.

java
int h = word.hashCode();
int bucket = Math.floorMod(h, 16);   // never negative
CallWhat it does
"".hashCode()0.
"a".hashCode()97, the code of 'a'.
"hello".hashCode()99162322.

Each step multiplies by 31 and adds the next char. With long strings the multiplication soon passes Integer.MAX_VALUE; the overflow wraps around silently, so hash codes can be negative.

Library declarations
java
public int hashCode();

Parameters

ParameterDescription
NonehashCode() takes no parameters.

Return Value

Return ValueDescription
intThe hash code of the string's characters (any int value, including negative ones).

Java Examples

Example 1 — Recompute the Hash by Hand

For a two-letter string the formula is short enough to write out.

java
public class HashCodeFormula {
    public static void main(String[] args) {
        String s = "hi";
        int manual = 'h' * 31 + 'i';

        System.out.println("manual:     " + manual);
        System.out.println("hashCode(): " + s.hashCode());
        System.out.println("empty:      " + "".hashCode());
    }
}

How It Works

  1. Two terms for two chars. With n = 2 the formula is s[0]*31 + s[1]; char arithmetic uses the codes 104 and 105.
  2. Same number. 104 * 31 + 105 = 3329, exactly what hashCode() returns.
  3. No chars, no sum. The empty string has nothing to add, so its hash code is 0.

Example 2 — Equal Strings Share a Hash Code

Two different objects with the same text, and two different texts with the same hash.

java
public class HashCodeEquality {
    public static void main(String[] args) {
        String a = "hello";
        String b = new String("hello");

        System.out.println(a.hashCode() + " " + b.hashCode());
        System.out.println("same object? " + (a == b));
        System.out.println("equal text?  " + a.equals(b));
        System.out.println("Aa vs BB: " + "Aa".hashCode() + " " + "BB".hashCode() + ", equal? " + "Aa".equals("BB"));
    }
}

How It Works

  1. Content decides the hash. The literal and the new String copy are different objects (== is false) but both hash to 99162322.
  2. The contract holds. Because the strings are equals, their hash codes must match, and they do.
  3. Collisions exist. 'A'*31 + 'a' and 'B'*31 + 'B' are both 2112, yet the strings differ; that is why hash tables also call equals.

Example 3 — Overflow and Negative Hash Codes

A famous string whose hash is exactly Integer.MIN_VALUE.

java
public class HashCodeOverflow {
    public static void main(String[] args) {
        int h = "polygenelubricants".hashCode();

        System.out.println("hash:  " + h);
        System.out.println("abs:   " + Math.abs(h));
        System.out.println("index: " + Math.floorMod(h, 16));
        System.out.println("Java:  " + "Java".hashCode());
    }
}

How It Works

  1. Wrap-around. Eighteen rounds of multiplying by 31 overflow the int range, and this string happens to land on -2147483648.
  2. abs() cannot help. The positive value 2147483648 does not fit in an int, so Math.abs returns the same negative number.
  3. A safe bucket index. Math.floorMod(h, 16) always returns 0 to 15; here it is 0. A short word like "Java" stays positive at 2301506.

Frequently Asked Questions

As s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] with int arithmetic, where s[i] is the i-th char. The empty string gives 0.
31 is an odd prime, which spreads values well, and 31 * x can be computed quickly as (x << 5) - x.
Yes. "Aa" and "BB" both hash to 2112. Hash codes narrow the search; equals() makes the final decision.
The int arithmetic overflows for longer strings and wraps around, so results can be anywhere in the int range, including negative values.
Yes. The formula is part of the String specification, so the same text always gives the same hash code.

Next: indent()

Add or remove leading spaces on every line (Java 12+).

indent() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful