For Integer type variable, does '=' operator equate the value or the reference?

CODE 1 :

Car car1 = new Car();
Car car2 = new Car();
car2.setColor("Green");
car2.setModel("I20");
car1 = car2;
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
car1.setColor("Red");
car1.setModel("I10");
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());

Output :

Green , I20
Green , I20
Red , I10
Red , I10

Here the car1 = car2; make the car1 object refer to car2 object thus any further change to car1 is equivalent to changing the car2 object as both are referencing to same value.

CODE 2 :

Integer c = 5;
Integer d = 10;
System.out.println(c + ", " + d);
c = d;
System.out.println(c + ", " + d);
c = 7;
System.out.println(c + ", " + d);

Output :

5, 10
10, 10
7, 10

Here also after c = d; both c and d refer to the same value then why changing the value of c does not change the value of d?

Upvotes: 0

Views: 67

Answers (2)

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

Integer is immutable. This means it cannot be changed that way. You are not allowed to change its internal fields. You are not allowed to change to what place in the memory it points to, but you are able to change the value that is assigned to the reference of given Integer. In example, when you write

Integer i = 5;
Integer j = 10;
i = j;

this doesn't mean that from now i is pointing to the same place in the memory where j points. It just assigns the value stored in j to i, because only that is allowed for immutable types.

Upvotes: 1

Evandro Mendes
Evandro Mendes

Reputation: 126

No because you assign value d in c not inverse. Do you understand ? If you desirre assing value c in d you write d = c for d recive reference of c

Upvotes: 0

Related Questions