Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.hashCode — a string's hash code

String.hashCode returns an int hash code calculated from a string's contents. Equal strings have equal hashes, but matching hashes do not prove that strings are equal.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public int hashCode()
int hash = text.hashCode();

String.hashCode is an instance method with no arguments that returns an int. It processes UTF-16 code units (char), not bytes or complete Unicode code points.

The calculation can be expressed as: start with h = 0, then for each code unit s.charAt(i), perform h = 31 * h + s.charAt(i). This uses int arithmetic, including overflow; the result can be negative. An empty string produces 0.

Strings equal according to equals have identical hashes. The reverse does not hold: "Aa" and "BB" both produce 2112, but are unequal. This is a collision. Use equals, not hash comparisons, to test equality; a hash is not a unique identifier.

Examples

public class Main {
    public static void main(String[] args) {
        System.out.println("".hashCode());
        System.out.println("abc".hashCode());
        System.out.println("Aa".hashCode());
        System.out.println("BB".hashCode());
        System.out.println("Aa".equals("BB"));
    }
}

Result

0
96354
2112
2112
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources