The reason you can change b
is because you're technically making a new String object and assigning it to the existing reference.
b += " World"
is the same as
b = b + " World";
b
is technically pointing to a new String object. So to start out, a
and b
are pointing to the same object, but when b
is modified it is now a different object, so a
will not equal "Hello World"
and a==b
will now be false.
For examples of mutable String classes, try StringBuffer
or StringBuilder
. You can use their .append()
method to add to the string, along with other methods to modify it.