Doubt with operator '=' several times in a statement

5

I would like to know why this code prints 3,1 and not another value:

Point a,b,c;

b = new Point(2,4);
a = new Point(3,1);
c = b = a;
c = new Point(1,2);
System.out.println(a);
    
asked by Negra 05.09.2016 в 05:20
source

1 answer

6

The assignment operator ( = ) is applied from right to left. That is, on the left operand the operation is performed taking the operand to the right.

In the specific case of c = b = a; the variable a is not modified by the assignment. The variables c and b in this case are assigned the object referenced by a .

The sentence is evaluated as c = (b = a) as indicated by @JoseAntonioDuraOlmos.

Now, your variables ( a b c ) are references to objects Point . They are not the object itself.

When you make c= New Point(1,2) you create a new object Point and this new object is referenced by c . You are not accessing the object referenced by c . It is not the semantics of = in the language for this case.

That's why when you print on the screen a you see (3,1) .

References:

Wikibooks - Programming in Java

SO-in - Initializing multiple variables to the same value in Java

    
answered by 05.09.2016 в 06:46