Ok, this is the way I understand this. There were 3 objects created: "abc" "ab" "c"
At first line, the reference variable x1 refers to "abc", at the second line, the ref var x2 refers to "ab". At the third line, x2 was concatenated with "c" so x2 now refers to "abc". My question is why is it that when x1 != x2 was executed, it returned true? As I understand it, both the reference variable x1 and x2 refers to the same object ("abc").
Ok, this is the way I understand this. There were 3 objects created: "abc" "ab" "c"
At first line, the reference variable x1 refers to "abc", at the second line, the ref var x2 refers to "ab". At the third line, x2 was concatenated with "c" so x2 now refers to "abc". My question is why is it that when x1 != x2 was executed, it returned true? As I understand it, both the reference variable x1 and x2 refers to the same object ("abc").
Paulo, To specifically answer your question, x1 and (the reassigned)x2 DON'T refer to the same object, so x1 != x2 holds.
Your example comes from K&B p.384. If you re-read that page and compare it to what they say about strings, literals, and the string pool on pp. 359-360, it makes sense why.
x1 above is a literal, so "abc" gets put in the pool. However, x2 = x2 + "c"; is not considered a literal, and so it won't match the "abc" literal already in the pool. If you had had, x2 = "abc", then x1 and x2 would refer to the same object in the pool.
Also, suppose you add to your code: String x3 = new String("abc");
In this case, does x1==x3? No. The object x3 is put in non-pool memory(because of the way it was constructed), so x1 and x3 don't refer to the same object. (But their content(value) is the same, so x1.equals(x3) holds.)
Again, compare those pages I mentioned above, run more tests with an eye to literals, non-literals, and the string pool and it becomes clear.
Pete. [ April 07, 2005: Message edited by: Pete Knecht ]