Java String hashCode() method example

Java String hashCode() method returns the hash code for the String. Hash code value is used in hashing based collections like HashMap, HashTable etc. This method must be overridden in every class which overrides equals() method.

Read More: Contract between hashCode() and equals() methods

1. String hashCode() method

The hash code for a String object is computed as:

s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

where :

s[i] – is the ith character of the string
n – is the length of the string, and
^ – indicates exponentiation

String hashCode() overrides the Object.hashCode(). It return the hash code as integer value.

2. Java String hashCode() example

Java program for how to calculate hashcode of string.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String blogName = "howtodoinjava.com";
        
        System.out.println( blogName.hashCode() );
        
        System.out.println( "hello world".hashCode() );
    }
}

Program output.

1894145264
1794106052

Reference:

Java String Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Java String hashCode() method example”

    • Both’re same, Bitwise operators like ^ & >>> >> are heavily used to decide hash across various api implementation classes. These’re tricky to understand, but very interesting if you try to understand why it’s been used.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.