Originally posted by John Ryan:
we are told that it will save memory.
If that's really what you've been told, you've been told nonsense. In either case, both "abc" and "def" will be in the string literal pool. They will be there from the very start. They are not created at run time, and never garbage collected. The very same String objects will be used every time your code is executed (remember, Strings are immutable).
So there is no difference in memory usage. There is however a difference in object creation - the first code listing has
better behaviour on the Sun JRE 1.4 because the String.concat() method produces a new String without using an intermediate StringBuffer. Your second listing produces a StringBuffer which is likely to be eventually turned into a String again, so there's one extra object being created.
There is a moral to this story: unless you know
exactly what you're doing,
don't try to be cleverer than Sun in managing Strings and StringBuffers[1]. You are likely to end up with worse rather than better behaviour.
- Peter
[1] You wouldn't believe the number of outfits who attempted to reduce object churn by implementing a StringBuffer pool. Why this is a bad idea is left as an exercise for the reader. Hint: follow the lifecycle of the char[] that backs both String and StringBuffer.
[ June 04, 2004: Message edited by: Peter den Haan ]