The String constructor that takes a string literal argument has the following implementation.
@IntrinsicCandidate
public String(String original) {
this.value = original.value;
this.coder = original.coder;
this.hash = original.hash;
}
From what I understand, the value of the original String literal(argument passed) gets assigned to the newly created object in the heap memory. So, we have two objects, one in the string literal pool and another in the heap memory. I'm assuming since the String literal pool does not get garbage collected, the created literal will stay in the literal pool till the end of the application. Isn't that waste of memory resources?
Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
I believe this comment from the source code, suggests that we do not use this constructor unless an explicit copy is needed, and it is unnecessary since Strings are immutable. Are they suggesting we don't use it since it is wasteful or is there any other reason behind that? If they are indeed suggesting not to use it since it is wasteful, why do they even have this and the parameter less constructor implemented(the comment there also says its unnecessary)?
Couldn't they have just had the constructors that take a character array, byte array etc... instead of these two constructors?
Java String creation and String pool
The above thread answers that a string literal does get created when you use new String("Argument"), but what I want to know is why they decided to have the String() and String("argument") if it is wasteful and they themselves are suggesting to not to use it?