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.
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.
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
Because c is created with new String, it gets given a different String object than a and b.
posted 4 years ago
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.
And will you succeed? Yes you will indeed! (98 and 3/4 % guaranteed) - Seuss. tiny ad: