class Temp {
public static void main(String[] args)
{
String a,b,c;
c= new String("mouse");
a=new String("Car");
b=a;
a= new String("Dog");
c=b;
System.out.println(c);
}
}
Here I am getting the output as Car. The same reference variable a has been instantiated twice. So the reference variable a should now point to the newly created object "Dog". As c is refering to b which is refering to a, the output is supposed to be Dog.
mvPrasad Regula wrote:As c is refering to b which is refering to a, the output is supposed to be Dog.
Java doesn't have assignment by reference. It has assignment by value (of references). So when you do,
b = a;
this does not mean that b becomes an alias for a and that both a and b are now two symbols for the same variable. That would be a by reference assignment and Java doesn't have that.
Instead what happens is that the value held by a (a reference) is replacing the value currently held by b. Afterwards the two variables a and b hold the same value (the same reference pointing at an object). This is an assignment by value of a reference and that's what Java does.
Java doesn't do anything by reference. It does everything by value, both assignments and parameter passing. The value assigned or passed can be a reference though.