The first code is shown below:
String s = "hello";
The second code is shown below:
String s = new String("hello");
Question: Are the two codes invoking the same constructor of String(char[])
?
String
has a private final field char value[]
. Why is it set to a final
field? Such we will create a new String
every time we invoke change the value of string. What is the purpose to set the field char value[]
to final
?
Question: Are the two codes invoking the same constructor of String(char[])?
No, absolutely not.
The first form bakes the the string content directly into the bytecode, then uses the ldc
(load constant) instruction to load it from the string pool.
Importantly, every occurrence of the string constant "hello" will refer to the same object.
Compare that with your second form, which will create a new string every time you execute the statement.
As to the details of the field being final: it's a private field anyway, so you shouldn't care. But it's final because Java strings are immutable - there's no reason why you'd want to change the value of it. (In itself that isn't enough to enforce immutability; anyone with access to that char[]
can modify the contents of the array.)
See more on this question at Stackoverflow