File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "String objects" Watch "String objects" New topic
Author

String objects

Vikram Nm
Greenhorn

Joined: Mar 29, 2001
Posts: 17
String s1=new String("hi");
String s2=new String("hi");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());

This prints out the same hashcode on my machine
shouldn't it be different since they are different objects
and are not using the pool.
Sandeep Nachane
Ranch Hand

Joined: Dec 06, 2000
Posts: 57
String Class overrides hashcode() method and looks at the contents of the string to determine the result of hashcode().
Sandeep Nachane


<A HREF="http://www.tipsmart.com" TARGET=_blank rel="nofollow">www.tipsmart.com</A>
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
This is in compliance with the general contract of the hashCode method defined by the Object -

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Since in your example s1.equals(s2) is true, s1.hashCode() must be equal to s2.hashCode().

FYI, the hashcode 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. (The hash value of the empty string is zero )


------------------
Ajith Kallambella M.
Sun Certified Programmer for the Java�2 Platform.
IBM Certified Developer - XML and Related Technologies, V1.


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String objects
 
Similar Threads
about String & StringBuffer
==, why is it so ?
HashCode same for strings with same values - Why?
String Comparison
meaningfully equivalent variables