Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

When are new String objects created  RSS feed

 
Ranch Hand
Posts: 686
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings

I am trying to resolve a conflict in information that is appearing in a java tutorial I am reading.

on the first page http://chortle.ccsu.edu/Java5/Notes/chap25/ch25_17.html it says that a new string object won't be created if the identical object already exists. Here this is described as an optimization.

on the second page http://chortle.ccsu.edu/Java5/Notes/chap26/ch26_20.html is an example that seems to directly contradict the first statement. In this example a second object is created when an identical object already exists. I verified this by running the example, and the == operator comparing the two references returned false.

So what am I missing?
 
author & internet detective
Sheriff
Posts: 38027
605
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you say "new String", a new String object is created. Strings are shared from the pool when you jsut reference them like:
 
Saloon Keeper
Posts: 8601
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "optimization" they were talking about in the first page was referring to assigning a String literal directly to the variable, as opposed to using the new keyword. The new keyword will always create a new object that has a different identity.

The page meant that the first time you use the literal "Green eggs", a new String object is created and remembered somewhere. The second time you use the literal "Green eggs", that object will be reused. This only works if you don't use the new keyword.
 
Bartender
Posts: 1844
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is the presence of the keyword "new" which creates a new object.
If you are just referring to String literals, because strings are immutable (can't change) the compiler reuses them automatically.



a == b ? true
a.equals(b) ? true
a == c ? false
a.equals(c)? true

Because c is created with new String, it gets given a different String object than a and b.

 
Fred Hamilton
Ranch Hand
Posts: 686
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick replies. It all makes sense now. And if I had read a few more pages I would have found the answer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!