This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
My qustion is what is the number of objects after concatenation? Similarly if we use replace() method on certain string object then whether it will create new string object or it will modify the existing object?
Now in total you have 3 objects : "A" , "B" and "AB" And one more thing in addition "B" object is eligible for Garbage Collection ...
This is false. You have 2 objects. One is an instance that has the value "A", the other is an instance that has the value "AB". "B" is not eligible for garbage collection because it is a String literal, not an object, and the same can be said for "A" and "AB".
The relevant part of the JLS is 15.28 where constant expression is defined. "A" + "B" is a constant expression and is inlined at compile-time.
"A" and "B" are both literals. For "A", there's also a String object in memory (at runtime) with length 1, containing the char 'A'. For "B", there could have been an object in memory, but since this is never needed at runtime, the compiler chose to omit it from the class file. "A" + "B" is a compile-time constant, which means that at runtime there is also a String object with length 2, contents 'A' and 'B'. Most of the time, we refer to a String object using either the literal or the variable name that refers to it. (E.g. "the String "A" or "the String myStr".) However in some discussions (such as this one) that's not sufficient, and we need to distinguish between an object and the things that refer to it. It's like names - on one level, I can say that I am Jim. But "Jim" is a name. I am not a name. Most of the time I don't need to make this distinction when talking to other people, but sometimes I do. Similarly, sometimes we need to distinguish between objects and the literals and variables that refer to them. [ March 08, 2005: Message edited by: Jim Yingst ]