String reversed = last + first;
No. It uses the data
last and in
to construct a new object.
No objects are 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 rather 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 will all work correctly when the object is changed.)
Objects of some Java classes
cannot be altered after construction.
String is one of these.
Sometimes immutable objects are called write-once objects.
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
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
can be altered (it can be made to point to a different
String object it refers to cannot be altered.
Inspect the following code:
String ring = "One ring to rule them all, " String find = "One ring to find them." ring = ring + find;
Does the last statement violate the rule that
Strings are immutable?