String reversed = last + first;
No. It uses data
in last
and in first
to construct a new object.
The other objects are not altered.
Java was designed after programmers had about 15 years of experience with object oriented programming. One of the lessons learned in those years is that it is safer to construct a new object than to modify an old one. (This is because many places in the program might refer to the old object, and it is hard to be sure that they can all deal with a change.)
Objects of some Java classes
cannot be altered after construction.
The class String
is one of these.
String objects are immutable. This means that after construction, they cannot be altered.
Sometimes immutable objects are called write-once objects. Once a String object has been constructed, the characters it contains will always be the same. None of its methods will change those characters, and there is no other way to change them. The characters can be used for various purposes (such as in constructing new String objects), and can be inspected. But never altered.
Confusion Alert!! This is a place where it is important
to distinguish between reference variables and their objects.
A reference variable referring to a String
can be altered (it can be altered to point to a different String object.)
The String
object it refers to cannot be altered.