Java – String hashCode() method

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

1. String’s 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)

1.1 Method Signature:

public int hashCode();

1.2 Returns:

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

2. 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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String indexOf() method
Java - String getChars() method