You're changing what a
refers to. Try this:
String a="a";
System.out.println("a 1-->"+a);
String b=a;
a="ty";
System.out.println("a 2-->"+a);
System.out.println("b -->"+b);
You will see that the object to which a
and then b
refers has not changed.
If you want to prevent your code from changing which object a
refers to, try:
final String a="a";