w3resource logo


Introduction to Java Programming

Java String: hashCode() Method

Secondary Nav

public int hashCode()

The hashCode() method is used to get a hash code from a given string. 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.

Note : The hash value of the empty string is zero.

Java Platform: Java SE 8

Syntax :

hashCode()

Return Value : a hash code value for this object.

Return Value Type: int

Example : Java String hashCode() Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args)
    {
        String str = "Java Exercises.";

        // Get the hash code for the above string.
            int hash_code = str.hashCode();
System.out.println();
        // Display the hash code.
System.out.println("The hash for " + str + " is " + hash_code);
System.out.println();
    }
}

Output:

The hash for Java Exercises. is -1762987343

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables