You are not changing the object in the assignment statement, you replace one immutable object with another one. Object String("a")
does not change to String("ty")
, it gets discarded, and a reference to ty
gets written into a
in its stead.
In contrast, StringBuffer
represents a mutable object. You can do this:
StringBuffer b = new StringBuffer("Hello");
System.out.writeln(b);
b.append(", world!");
System.out.writeln(b);
Here, you did not re-assign b
: it still points to the same object, but the content of that object has changed.