Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

All about Strings

 
Manish Chhetri
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between String x="hello"; and String x=new String("hello") in terms of the object creation and the reference. Is there any difference in the way memory is allocated for these two type of String declarations.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Welcome to JavaRanch!
In the first case (without the new) the String comes from a pool of unique strings held internally by the JVM; literal Strings are put into this pool when the classes defining them are loaded. In the second case, a new String object is allocated at that point while the program is executing.
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All string constants are dumped into the CONSTANT_POOL at compile time. In the following example:

When this compiles there are two string constants placed in the constant pool, one for "A string" and one for "B string". However at runtime both 'one' and 'two' would reference the same string, while new string instances would be created for 'three', 'four' and 'five', as Ernest pointed out.
So "one == two" would evaluate to "true", but any other combination of strings would evaluate to "false" when doing an "==". That's why it's always safest to use ".equals()" when doing string comparison, unless you actually want to see if the two strings reference the same underlying String instance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic