Java.lang.String.hashCode() Method
Advertisements
Description
The java.lang.String.hashCode() method returns a hash code for this 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
Declaration
Following is the declaration for java.lang.String.hashCode() method
public int hashCode()
Parameters
NA
Return Value
This method returns a hash code value for this object.
Exception
NA
Example
The following example shows the usage of java.lang.String.hashCode() method.
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
Integer i = new Integer(50);
Long l = new Long(50);
Float f = new Float(50);
Integer i2 = new Integer(0);
// hash codes of different objects with same value are always same
System.out.println("Hash code of " + i + " is = " + i.hashCode());
System.out.println("Hash code of " + l + " is = " + l.hashCode());
// hash code for float value i.e different from Integer and Long
System.out.println("Hash code of " + f + " is = " + f.hashCode());
// hash code value of number zero(0) is zero(0)
System.out.println("Hash code of " + i2 + " is = " + i2.hashCode());
String str = "this is tutorialspoint";
// hash code of string str
System.out.println("Hash code of string is = " + str.hashCode());
}
}
Let us compile and run the above program, this will produce the following result:
Hash code of 50 is = 50 Hash code of 50 is = 50 Hash code of 50.0 is = 1112014848 Hash code of 0 is = 0 Hash code of string is = 643938959