I'd say 6 (but I'm not sure), here's why: The objects "java", "exam" and " " are created in the string constant pool, the objects pointed to by the references s1 and s2 are created on the heap and the String object created by the addition (s1 + " " + s2) is created on the heap so you have 3 objects in the string constant pool and 3 on the heap, but I'm just guessing as I'm not sure what really goes on when you create a String with the overloaded "=" operator. Perhaps s1 and s2 point to objects in the constant pool rather than the heap? Can anyone clarify? Nick
Nick<br />SCJP<br />SCJD
Joined: Jul 17, 2003
I've changed my mind, I think it's 4. If the overloaded "=" operator creates objects on the heap then there is no point in having a String constant pool to save memory, so I reckon s1 and s2 point to objects in the constant pool, so there's 3 in the pool and 1 on the heap (the one made by the addition) - err or does that one go in the pool too? Anyway I say 4 Nick - realised he doesn't understand how Strings work
I would say that there are THREE string objects created during the compile time, "java", "exam", " " and one string object created at runtime, "java exam". However, if you declare s1 and s2 as final, then there would still THREE string objects created during compile time, but they are "java", "exam" and "java exam". And there will be no objects created at runtime.