Biswanath Chowdhury
Biswanath Chowdhury

Reputation: 257

Hashcode Of a String

When we try to print any object using toString() we get the HashCode (if toString() is not overriden). But, If I want to print the Hashcode of the String Variable, what should I do. This question it is with respect to Java.

Upvotes: 1

Views: 3361

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200138

You can get the hash code of any Java object by invoking the hashCode() method. The result will be an int that you can then print or do anything else you want with it.

If you are interested in the implementation of Object.toString, it is very easy to check at grepcode. It says:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Upvotes: 2

Petar Minchev
Petar Minchev

Reputation: 47363

Simply call the hashcode() method. It comes from Object.

String str = "mystring";
System.out.println(str.hashCode());

Upvotes: 1

Boris Pavlović
Boris Pavlović

Reputation: 64622

System.out.println("Some String".hashCode());

Upvotes: 2

Jesper
Jesper

Reputation: 206766

Just call hashCode() on the String object:

String s = "Hello World";
System.out.println(s.hashCode());

If you want it in the same format as Object.toString(), try this:

System.out.println(Integer.toHexString(s.hashCode()));

Upvotes: 8

Related Questions