When creating a String object in Java, then concatenating something else to it via
someString.concat("I am being concatenated to someString");
or somesuch, since Strings are immutable, a temporary object is created that contains the resulting string, correct? Usually, when this is done, a new String object is created right away to contain it, something like
String newString = oldString.concat("I am being concatenated");
but suppose that it isn't. In that case, would there be another way to access the concatenated string? (In this last case, the sum of oldString and "I am being concatenated".)
Variables of non-primitive types in Java are references, they are not the objects themselves (as in C++). In a line like this:
String newString = oldString.concat("I am being concatenated");
there is not a new String
object created in which the content of the imagined temporary string is copied. In fact, newString
is going to refer to what you think is the temporary object. (There is not really a temporary object).