The String.hashCode() method computes and returns a signed 32-bit integer hash code representing the string's character sequence.
Deterministic Polynomial Formula & Caching: Java computes hash codes using the exact polynomial formula s[0]*31^(n-1) + ... + s[n-1]. The result is cached internally after the first computation for instant O(1) lookups. To verify value equality, see equals(). For lexicographical sorting, explore compareTo(). For measuring length, see length(), or verify empty strings with isEmpty().
The hashCode() method is inherited from Object and overridden in java.lang.String:
// Formal signature of String.hashCode() in java.lang.String
public int hashCode()
| Signature Element | Type | Description & Operational Contract |
|---|---|---|
| Parameters | None | Takes zero arguments; operates on the calling string instance. |
| Return Value | int |
A signed 32-bit integer (can be positive, zero, or negative). |
| Time Complexity | O(N) first call / O(1) cached |
Computed once in linear time, then cached in a private field. |
Demonstrating hash outputs across different strings, case variations, and empty strings:
String s1 = "plus2net";
String s2 = "welcome";
String s3 = "WELCOME";
String empty = "";
System.out.println("plus2net: " + s1.hashCode()); // -1850174267 (negative integer)
System.out.println("welcome: " + s2.hashCode()); // 1233099618
System.out.println("WELCOME: " + s3.hashCode()); // 1951082306 (case-sensitive)
System.out.println("empty: " + empty.hashCode()); // 0 (empty string is always 0)Terminal Output:
plus2net: -1850174267
welcome: 1233099618
WELCOME: 1951082306
empty: 0
Java defines the string hash code using a deterministic polynomial equation:
Polynomial Formula: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
In this formula, s[i] represents the character value at index i obtained via charAt(i), and n represents length(). Java uses the prime number 31 because:
31 * i as a single bit-shift instruction: (i << 5) - i.We can verify this formula by calculating it manually with a for loop:
// Replicating Java's exact formula: h = 31 * h + s.charAt(i)
String word = "Hi";
int h = 0;
for (int i = 0; i < word.length(); i++) {
h = 31 * h + word.charAt(i);
}
System.out.println("Calculated hash: " + h); // 2337
System.out.println("Built-in hash: " + word.hashCode()); // 2337 ('H' * 31 + 'i' = 72 * 31 + 105 = 2337)Terminal Output:
Calculated hash: 2337
Built-in hash: 2337
Java enforces a strict contract between equals() and hashCode():
| Contract Rule | Requirement | Implication for Developers |
|---|---|---|
s1.equals(s2) == true |
Mandatory | Hash codes must be identical: s1.hashCode() == s2.hashCode(). |
s1.hashCode() == s2.hashCode() |
Optional | Strings might be equal, or might be a hash collision. |
String strA = new String("Java");
String strB = new String("Java");
// 1. Equal strings MUST have identical hash codes
System.out.println("strA.equals(strB): " + strA.equals(strB)); // true
System.out.println("strA.hashCode(): " + strA.hashCode()); // 2301506
System.out.println("strB.hashCode(): " + strB.hashCode()); // 2301506
System.out.println("Same hash code? " + (strA.hashCode() == strB.hashCode())); // trueTerminal Output:
strA.equals(strB): true
strA.hashCode(): 2301506
strB.hashCode(): 2301506
Same hash code? true
Because there are infinite possible strings but only 2^32 distinct 32-bit integers, different strings will occasionally share the exact same hash code. This is called a hash collision:
// Famous Java String hash collisions
String pair1A = "FB";
String pair1B = "Ea";
System.out.println("pair1A hash: " + pair1A.hashCode()); // 2236
System.out.println("pair1B hash: " + pair1B.hashCode()); // 2236
System.out.println("Are strings equal? " + pair1A.equals(pair1B)); // false!
String pair2A = "Aa";
String pair2B = "BB";
System.out.println("pair2A hash: " + pair2A.hashCode()); // 2112
System.out.println("pair2B hash: " + pair2B.hashCode()); // 2112Terminal Output:
pair1A hash: 2236
pair1B hash: 2236
Are strings equal? false
pair2A hash: 2112
pair2B hash: 2112
Because hash codes can be negative, taking a simple modulo hash % count can produce invalid negative indices. Masking with 0x7FFFFFFF clears the sign bit:
public class HashBucketMapper {
public static int getBucketIndex(String key, int bucketCount) {
if (key == null) return 0;
// Mask with 0x7FFFFFFF to convert negative hashes to non-negative integers
int nonNegativeHash = key.hashCode() & 0x7FFFFFFF;
return nonNegativeHash % bucketCount;
}
public static void main(String[] args) {
int buckets = 16;
System.out.println("Bucket for 'alpha': " + getBucketIndex("alpha", buckets));
System.out.println("Bucket for 'plus2net': " + getBucketIndex("plus2net", buckets));
}
}Terminal Output:
Bucket for 'alpha': 14
Bucket for 'plus2net': 11
Because strings are immutable, the hash code can never change after initialization. Java stores the value in a private field hash so subsequent calls return immediately:
String article = "Modern Java tutorial for enterprise architectures";
// First call: scans string and caches result in internal private 'hash' field in O(N) time
long t0 = System.nanoTime();
int h1 = article.hashCode();
long elapsed1 = System.nanoTime() - t0;
// Second call: directly returns cached value in O(1) time
long t1 = System.nanoTime();
int h2 = article.hashCode();
long elapsed2 = System.nanoTime() - t1;
System.out.println("Hash code: " + h1);
System.out.println("Second call executed instantly via cached field.");Terminal Output:
Hash code: 2026118491
Second call executed instantly via cached field.
String.hashCode() is designed for hash tables, not cryptographic security. Do not use it for password hashing or checksums. For secure digests, use SHA-256 via getBytes().
Calling Math.abs(str.hashCode()) to make a hash positive fails if the hash equals Integer.MIN_VALUE (-2147483648), because Math.abs(Integer.MIN_VALUE) returns negative! Always mask with hash & 0x7FFFFFFF.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringHashCodeFullDemo {
public static void main(String[] args) {
String test = "plus2net";
// 1. Verify predictable hash calculation
if (test.hashCode() == -1850174267) {
System.out.println("Check 1 Passed: Known string hash code verified.");
}
// 2. Verify empty string has hash 0
if ("".hashCode() == 0) {
System.out.println("Check 2 Passed: Empty string hash code is exactly 0.");
}
// 3. Verify collision handling
if ("FB".hashCode() == "Ea".hashCode() && !"FB".equals("Ea")) {
System.out.println("Check 3 Passed: Hash collision detected and verified.");
}
System.out.println("All String.hashCode() verification checks passed successfully!");
}
}Terminal Output:
Check 1 Passed: Known string hash code verified.
Check 2 Passed: Empty string hash code is exactly 0.
Check 3 Passed: Hash collision detected and verified.
All String.hashCode() verification checks passed successfully!
Yes. Java integers are signed 32-bit values. Arithmetic overflow during polynomial multiplication frequently produces negative results.
The hash code of "" is always 0, as specified in the Java language specification.
Yes. Because the polynomial formula is explicitly defined in the Java specification, a given string will produce the identical hash code on any compliant JVM.
Yes. Calling null.hashCode() crashes with a NullPointerException. Check that the reference is non-null before invoking.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.