First, String
literals composed of the same characters resolve to the same instance. So in
String one = "hello";
String two = "hello";
both variables are referring to the same object.
Second, static
initializer blocks are executed when a class is first loaded (and initialized). This occurs before any class methods are invoked, ie. before main
.
Third, your Java version's implementation of String
, presumably, uses a char\[\]
field to store the string of characters. This field is named value
.
You're using reflection to retrieve this char[]
for the String
object referenced by the String
literal "Howdy"
.
Field value = String.class.getDeclaredField("value");
...
value.get("Howdy")
and assigning it to the char[]
field of the String
object referenced by the String
literal "Hello"
value.set("Hello", value.get("Howdy"));
Now, when your main
method executes
String a = new String("Hello");
the String
literal "Hello"
is referencing the same object for which you set the char[]
field previously. This char[]
contains the characters 'H'
, 'o'
, 'w'
, 'd'
, and 'y'
since it was taken from the String
object referenced by the literal "Howdy"
.
These characters are copied into a new String
object created here
String a = new String("Hello");