Java String hashCode() – What’s the Use?

Java String hashCode() method returns the integer hash code value of this string. String class overrides this method from Object class.

How Does Java Calculates String Hash Code?

The string hash code calculation follows the below logic.

int hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1];
  • Here s[i] is the character at ith index. 
  • ^ indicates exponentiation
  • n is the length of the string.

The hash code of an empty string is 0.

Java String hashCode() Examples

Let’s have a look at some examples of String hashCode() method.

package net.javastring.strings;

public class JavaStringHashCode {

	public static void main(String[] args) {
		String s1 = "Java";
		String s2 = "Java";
		String s3 = new String("Java");




Java String HashCode Example
Java String hashCode() Example

Java String hashCode() and equals() Contract

  • If equals() is true for two strings, their hashCode() will be the same.
  • If two strings hashCode() is equal, it doesn’t mean they are equal.

The first statement will always be true because string characters are used to calculate the hash code. You can confirm this from the above java program too.

Let’s look at some code snippets to confirm the second statement.

String a = "Siblings";
String b = "Teheran";

System.out.println(a.hashCode() == b.hashCode());

Here is the output when the above code snippet is executed in JShell.

Java String HashCode And Equals Contract
Java String hashCode() and equals() Contract

Java String hashcode Collision

When two strings have the same hashcode, it’s called a hashcode collision. There are many instances where the hash code collision will happen. For example, “Aa” and “BB” have the same hash code value 2112.


We shouldn’t rely on the hashCode() method to check if two strings are equal. String class overrides this function from Object class. It’s used by Java internally when String is used as Map key for get() and put() operations.