Library contents

Java String.hashCode

Compute Java’s integer content hash, as used by hash-based collections.

A simple example

String.hashCode

  1. Start with "A"
  2. Do this Calculate the string hash
  3. Result 65
For a one-character Java string, its hash equals the numeric value of that character.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A".hashCode());
    }
}
Output
65

Syntax

Java syntax
public int hashCode()
JDK 21 method signatures (1)
public int hashCode()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Match a freshly scanned catalog key

A freshly scanned catalog key arrives as a separate object from the stored key. Check its text and lookup behavior before deciding whether the scanner has identified an existing item.

From the programSystem.out.println(scan.hashCode() == "A7".hashCode())
Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String scan = new String("A7");
        System.out.println(scan.hashCode() == "A7".hashCode());
    }
}
Output
true

Equal strings have the same hash even when they are different objects.

Advertisements

See why equal hashes cannot identify customers

A catalog uses text as a lookup key and also computes a hash for indexing. Compare the keys themselves when deciding identity, because two different labels can share a hash value.

From the programString first = "Aa"
Resulttrue / false
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String first = "Aa";
        String second = "BB";
        System.out.println((first.hashCode() == second.hashCode()) + " / " + first.equals(second));
    }
}
Output
true / false

These two different strings collide under Java’s string hash.

Read a parcel sorting code

The depot scans a parcel marked NC-17. A Java-based scanner logs the String hash of the complete identifier for a diagnostic comparison. What decimal hash does it record?

GivenNC-17
Worked result74075454

What to watch for

Distinct strings can have the same hash. Use equals to establish identity and avoid using hashCode for secrets.

Documentation for String.hashCode