I had posted some
String trivia questions for a friend of mine and he responded with this one, which got me. I thought it was excellent to know because I would *think* this type of question could be on the exam.
I will purposely insert a number of blank lines to give you time to think of the answers before reading them.
Ready? Here they are:
false
true
false
false
false
false
Yep, the only one that has a matching reference is (a==c). Now, the big question is why? Here's my interpretation, but I'm not certain that it is 100% correct.
First, note that if String d had said:
String d = new String("AB");
then the answers would still have been exactly the same.
Now remember that a String object lives on the heap, but the value lives in the StringPool (an area of memory that I'm guessing lives on the heap???)
Thus, when String c is created, it looks at the StringPool, says, "oh, here is a string called AB, and a String object that refers to it. So it gives c the reference to the String object that a refers to.
Now, I'm guessing that in the case of String b and String d (and I'm ignoring the strings that get created in the construction that are discarded..."A" and "B"), it is told to create a new String object on the heap, which would thus have a different reference for each newly created String object on the heap. Subsequently, it looks in the StringPool and says, "Ah ha! There is an AB in here!" So it gives the String object the reference to AB in the StringPool (which would presumably then be the same reference to AB in the String object for String a and String c). However, the String object itself---not its value---had a new instance created and thus has a different reference.
This would explain the results above, but my visual representation could be way off since I assume (1) the StringPool lives in the heap and (2) that the String object contains a reference to an object in the StringPool.
I want to ensure I'm understanding or interpreting this correctly.
Thoughts? Comments?
Ross