w3resource

Java String: hashCode() Method

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:

Previous:getChars Method
Next:indexOf Method



Follow us on Facebook and Twitter for latest update.