posted 13 years ago
Something it took me a long time to 'get was that Strings work differently than other objects. Any time you see a literal string (something enclosed in double quotes), a String is made and put into the 'String pool'. If the exact same literal is seen more than once, like your "abc", the string is created one time, and both references point to the same String object.
Now, ANY time you see the 'new' operator used, that means a new object is created. So when you do "new String("foo")", you get TWO objects created. A string is put in the String pool for the "foo" literal (unless "foo" was already used somewhere else prior to this line), and a SECOND String object is created, this time NOT in the String pool, which also has a value of "foo". You get two-for-one when you write it that way.
which is why99% of the time, you shouldn't.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors