Perhaps some pictures will make it clear, although my reliance on ASCII art to do the pictures may reduce the clarity somewhat...
Any time you have an object, a variable (or parameter) of that object really holds a "reference" or "pointer" to the object, not the object's value. A String
is an object in Java, but this answer really applies to any kind of object. I've sometimes explained it this way: Think of an object as a house, and a reference is a piece of paper with the address of the house written on it. If you make a copy of the reference, you're creating a new piece of paper, but it has the same address written on it. So there's still just one house.
So here's the situation after each line of code:
String abc="abc";
variable abc
|
|
v
---------------
| abc | (String object.)
---------------
Now:
String xyz=abc;
You're copying the reference, so now you have two variables pointing to the same object:
variable abc variable xyz
| |
| +---------+
v v
---------------
| abc | (String object.)
---------------
These two variables point to the same object, but they are still two separate variables. So if you change the variable abc
, it has no effect on xyz
, which still is a reference to the same object. That is, after this:
abc = "acvb";
variable xyz variable abc
| |
+---------+ |
v v
--------------- ----------------
| abc | | acvb |
--------------- ----------------
So now, abc==xyz
is false because they're not pointing at the same object.