my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String reference 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 "String reference" Watch "String reference" New topic

String reference

Diane Cheng

Joined: Jul 30, 2003
Posts: 7
The following is from
Note that if you construct two Strings with the same String literal, without using the new keyword, e.g.
String a = "Hello"
String b = "Hello"
, then Java creates only one String object, so a==b evaluates as true.
I think a==b should evaluate as false since they are pointing to two different String object.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
String literals are stored in the String pool without duplicates so they do point to the same String.
Compare this:
String a = "JAVA";
String b = "JAVA";
System.out.println(a == b);
to this:
String a = new String("JAVA");
String b = new String("JAVA");
System.out.println(a == b);

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Diane Cheng

Joined: Jul 30, 2003
Posts: 7
Thanks Thomas.
I agree. Here's the link:
subject: String reference
It's not a secret anymore!