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 = "";
        System.out.println( blogName.hashCode() );
        System.out.println( "hello world".hashCode() );

Program output.



Java String Doc

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

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.


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.