Because x
is a reference (or a variable of reference-type). All the first piece of code does is re-point the reference at a new value. For example
String y = "Jim";
String x = y;
y = "Bob";
System.out.println(x); //prints Jim
System.out.println(y); //prints Bob
The fact that you are re-assigning the reference y
to "Bob" does not affect what the reference x
was assigned to.