The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

which hash code will be returned by String object

Posted by jinaraj on December 04, 2001 at 4:27 AM

If you create a String object with keyword "new ", one object is created in heap apart from one getting created in pool. But which hashcode will be returned if hashCode() method is invoked? The hashcode of the pooled object or the heap object? I shall write a small piece of code for clarity.

String s1="Hello";
String s2="Hello";

System.out.println(if(s1==s2));
// This will return true.

String s3 = new String("Hello");
System.out.println(if(s1==s3));
// This will return false.
System.out.println(s1.hashCode());
System.out.println(s3.hashCode());
//These two print outs gives the same result.

My understanding is when you apply == it is the hash codes getting copared.
If this is true, s1.hashCode() and s3.hashCode() should return the same same result. But it is not.

Please tell me what is happening here.






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us