For instance, consider the following
code:
StringBuilder sb = new StringBuilder();
(I have used StringBuilder as a random
example of a reference type - there's nothing special about it.) Here, we
declare a variable sb, create a new StringBuilder object, and assign to sb a
reference to the object. The value of sb is not the object itself, it's the
reference. Assignment involving reference types is simple - the value which
is assigned is the value of the expression/variable - i.e. the reference.
This is demonstrated further in this
example:
StringBuilder first = new StringBuilder();
StringBuilder second = first;
Here we declare a variable first,
create a new StringBuilder object, and assign to first a reference to the
object. We then assign to second the value of first. This means that they
both refer to the same object. They are still, however, independent
variables themselves. Changing the value of first will not change the value
of second - although while their values are still references to the same
object, any changes made to the object through the first variable will be
visible through the second variable.
|