class test{ public static void main(String args[]){ Integer b,a; a = 4; b = a; a = 334; System.out.println(b); } } 

Why in this case b did not change the value? isn't it a reference type, like a class object.

  • Because you change the link itself contained in the variable, and not the value of the link. - etki
  • The above code is probably equivalent to a = new Integer (4); b = a; a = new Integer (334); - keekkenen

1 answer 1

Object (or reference) type variables store references to the objects themselves.

In the line a = 4; An object of class Integer and the reference to this object is placed in the variable a .

In the string b = a link stored in the variable a copied into the variable b . After that, the variables a and b refer to the same object.

Further, in the line a = 334; An object of class Integer and a reference to it is placed in the variable a . There is no manipulation of the variable b .

* if an object with the same value was created earlier and it is stored in a pool, then a new object will not be created, instead an object from the pool will be used.