Share on Google+Share on Google+

java.lang.String.hashCode()

Advertisement
int hashCode() method in Java returns a hash code for the given string but it can return zero as well if the given string is empty.

int hashCode() method in Java returns a hash code for the given string but it can return zero as well if the given string is empty. It can be computed as ..

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

Where..

i -> is a first character

n-> length of the string

^ indicates exponentiation

See the example given below that explains how to get the hashCode for any given string in Java.

a simple hashCode example:

public class StringTrim {

public static void main(String[] args) {

String str = "Java Examples Code";

System.out.println("Corresponding hash code value returned is: "

+ str.hashCode());

}

}

the output is:

Corresponding hash code value returned is: 1275699718

Related Examples:
Java BigDecimal hashCode example

 

Advertisements

Posted on: March 22, 2005 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.