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 in robust code it is safer to construct a new object than to modify an old one. (Because the old object may be referred to in many places, some of which are not expecting a change.)
So, for many Java classes
objects cannot be altered after construction.
The class String
is one of those.
String objects are immutable. This means that after construction, they cannot be altered.
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.
The String
object it refers to cannot be altered.