0

There is a code:

class A {
    int x = 12;
}
public class Program {
    public static void main(String [] args) {
        A a = new A();
        int d = 10;
        a.x = d;

        System.out.println("a.x: " + a.x + ", d: " + d);

        d = 52;
        System.out.println("a.x: " + a.x + ", d: " + d);
    }
}

The output is:

a.x: 10, d: 10
a.x: 10, d: 52

Why a.x doesn't change? As I understand during the assignment the left value take a reference of the right value, and if right value will changed after, the left value must change too. Why it doesn't happen?

Cœur
  • 37,241
  • 25
  • 195
  • 267
luckystrrrike
  • 265
  • 3
  • 11
  • 1
    "As I understand during the assignment the left value take a reference of the right value, and if right value will changed after, the left value must change too." What makes you think that? The assignment operator simply copies the value from the right hand of the operator to the variable on the left hand (with any conversions as required). – Jon Skeet May 06 '16 at 10:45
  • I read something like it in 'Thinking in Java' – luckystrrrike May 06 '16 at 10:47

4 Answers4

2

please re-assign your variable a.x using d because x is a int and object member of Class A. So, assignment of value is taking place rather than Reference.

Thank you.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
2

This is because you are using primitives. Values are copied, not references.

If you were to use objects, then they would have the same reference and have the outcome you expected.

stefana
  • 2,606
  • 3
  • 29
  • 47
1
int d = 10;
a.x = d;

What you did here, you copied d to place in memory where a.x is (note: you are dealing with primitives not with objects, so no references, as with objects). So you have 10 on two places, for d and for a.x. Next, you change value d = 52; You changed for d, but a.x has its own value, which is 10.

Same thing happens when you have:

A a2 = new A();

and you do something like:

a2.x = a.x;
a.x = 50;

a2.x will be 10 because its another object with its own primitive x, and you copied value to it, and changing one of them is simply changing it, not the other one. But if you do this:

A a2 = new A();
a = a2;
a.x = 52;

Then a2.x will be 52, since you changed reference of a to point to object which is referenced with a2 (object which was referenced with a until then will hang free, so GC will deleted when it decides to), so now a2.x and a.x are the same primitive.

Adnan Isajbegovic
  • 2,227
  • 17
  • 27
0

You never re-assigned a.x to a new value.

The instance A a = new A(); still got the old d value because it basically copied it into memory at that point of time.

Later on you assigned a new value to d, which does no impact to instance a since primitives are not references. They're not linked together.

codex
  • 45
  • 6