Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String reference

 
Diane Cheng
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following is from http://www.jchq.net/essentials/d0e1214.htm:
----------------------------------------------------------------------
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
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
 
Diane Cheng
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic