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:

 

 

Happy Coding !!
Happy Learning !!

Java: String indexOf() method
Java: String getChars() method