0

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".)

4 Answers 4

3

I would say no, because you create a new object in the heap-space but have no reference to it. So it will be garbage collected. In Java there is no way to directly access heap-space-addresses ...

2

concat does indeed create a new String object (not sure what you mean by temporary), and if you don't store the reference of that new String in a variable there is no way you can access it later.

In practice:

someString.concat("I am being concatenated to someString");

will probably be eliminated as dead code at some stage (when/if the code gets compiled by the JIT compiler).

1

See accepted answer for a correct one but a crazy reply might be...

someString.concat("I am being concatenated to someString").intern();
// later on later on in the code...
String s = new String("I am being concatenated to someString").intern();
0

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.