I know that the title of the question is not very clear, sorry about that, did not know how to put it up. I have a very basic java implementation question which I want to fo
You are actually showing 3 different reasons why the Strings may use the same buffer internally. Note that sharing a buffer is only possible for separate instances because they are immutable; otherwise changes in the buffer would be reflected in the other variable values as well.
Compiler detects identical String literals; if the string literal is repeated the compiler may simply point to the same object instance;
References to a String are pointing to the same object instance and are therefore identical by definition;
Buffer sharing may help during construction with new
. If the runtime system sees that String contents may be shared then it may opt to do so; this behavior is however not guaranteed - it's implementation specific. The object instances should be different (but using them as separate instances would still not be wise).
As an example for #3, Java 6 OpenJDK source simply will point to the same buffer. If the buffer is larger than the new String
instance, a copy will be created. Those are different Objects explicitly, a new String Object will created for each call, though it could reuse char array of the underlying string (the one you provide in constructor) so that the Garbage Collector can clear the larger string (otherwise the larger character buffer may be kept in memory indefinitely).
This all should not matter too much to you, unless you get careless and start using ==
for equality (or other constructs that confuse ==
with equals
).