Java: String hashCode() method

In this article, we will discuss how to get hash code for any string using String’s hashCode() method

 

hashCode() method: This String method is used to get hash code for invoking string. The hash code for a string object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, 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 (0)

 

Method Signature:

public int hashCode();

 

Returns:

  • Returns a hash code for the invoking string of int data-type

 

Examples on hashCode() method:

Sample Java program to get hash code for the invoking string

StringHashCodeMethod.java

package in.bench.resources.string.methods;

public class StringHashCodeMethod {

	public static void main(String[] args) {

		String str = "BenchResources.Net";
		System.out.println("Hash Code value : " + str.hashCode());
	}
}

Output:

Hash Code value : 1514055172

 

References:

https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

 

Happy Coding !!
Happy Learning !!