posted 18 years ago
Jim is right, but he doesn't qualify his statement enough.
For String (which is what we're talking about here) he is right.
For some other class he may not be (as each class can and often will have a distinct hascode algorithm relevant to the data contained within an instance of that class).
You are correct in assuming that garbage collection for Strings in the String constant pool is different from garbage collection of any object anywhere else, but that's not relevant in this scenario as the question was how many objects are created, not how many exist at the end of the code block (the answer to that could be undefined even).
In this scenario, at most 3 objects are created on the string constant pool.
A total of 4 references are created, 2 each to 1 of these objects.
The last of them ("Pal") has no reference at all but does exist and would be reused if another assignment 's5 = "Pal";' were added.
I had to qualify my statement with "at most" because as Kristian notes any one or more of the strings may already have existed in the string constant pool and therefore might not have been created at all, but during the exam you can (almost, it will be explicitly mentioned if not) assume that such situations will not occur (in fact, because of tricks like this you're highly unlikely to see questions like this using String as a datatype on the real exam).