Java String hashCode() Method Tutorial

In this section, we will learn what the String hashCode() method is and how to use it in Java.

What is Java String hashCode() Method?

The `hashCode()` method is used to get the hash code of a string value.

Java hashCode() Method Syntax:

public int hashCode()

hashCode() Method Parameters:

The method does not take an argument.

hashCode() Method Return Value:

The return value of this method is an integer value, which is the hash code of the target string value.

Example: using String hashCode() method

public class Simple {

    public static void main(String[] args)  {
        String s1 = "BE KING TO ONE ANOTHER";
        System.out.println(s1.hashCode());
    }
}

Output:

-1373947600

The formula that is used to get the hash code of a String is as follow:

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

  • The `s[i]` is the `i`th character of the string.
  • The `n` is the length of the string.

The ^ indicates exponentiation.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies