File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question about String. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about String." Watch "A question about String." New topic

A question about String.

Jianfeng Qian
Ranch Hand

Joined: Jan 25, 2005
Posts: 83
public class Tester {
public static void main(String[] args) {
String s="Dont";
String s1 = "Dontcry";
String s2 = "Dont"+"cry";
String s3=s+"cry";
String s4=s+"cry";
System.out.println("s1 == s2?"+(s1 == s2));
System.out.println("s3 == s4?"+(s3 == s4));
} // main()
} // Tester
s1 == s2?true
s3 == s4?false
//why s3!=s4?

Jianfeng Qian<br />SCJP 1.4, SCBCD 5.0(beta)
Bilal Al-Sallakh

Joined: Jan 28, 2005
Posts: 20
"Dont"+"cry" is evaluated at compile time to "Dontcry" which is already in the strings-literals pool, while (s + "cry") is evaluated at runtime and the result is a new string stored in the heap (not in the pool), so s3 and d4 will refer to different objects.

If you mean why the compiler doesn't evaluate it at copmile time, consider a more general case where s is not local to the method: how can the compiler garantee that s doesn't change?

Hope this helps
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
To illustrate Bilal's point, change
String s="Dont";
to this
final String s="Dont";

You will get:
s1 == s2?true
s3 == s4?true

Mike Gershman
SCJP 1.4, SCWCD in process
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
as a general rule, one should never use == to test for equality between object instances.

== checks whether 2 references refer to the same object instance in memory, not whether they refer to 2 object instances containing the same data.

Vincent Brabant
Ranch Hand

Joined: Nov 01, 2004
Posts: 33
Please try this code:

System.identityHashCode() method return the same hashcode an object would have been given by the default Object.hashCode() method.
And because the default hashCode() method is it's memory address expressed as an int, you will directly see if references are pointing to the same memory location.

Hope it can help you.

Vincent Brabant<br /><a href="" target="_blank" rel="nofollow"></a>
Jianfeng Qian
Ranch Hand

Joined: Jan 25, 2005
Posts: 83
Thank you ! Now I understand it
I agree. Here's the link:
subject: A question about String.
It's not a secret anymore!