This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.
String s1="Hi";
String s2=s1;
s1="Bye";
System.out.println(s2); //Hi (if String was mutable output would be: Bye)
System.out.println(s1); //Bye
s1="Hi"
: an object s1
was created with "Hi" value in it.
s2=s1
: an object s2
is created with reference to s1 object.
s1="Bye"
: the previous s1
object's value doesn't change because s1
has String type and String type is an immutable type, instead compiler create a new String object with "Bye" value and s1
referenced to it. here when we print s2
value, the result will be "Hi" not "Bye" because s2
referenced to previous s1
object which had "Hi" value.