2

This is allowed by the Java compiler, what is it doing?

int x = x = 1;

I realize that x is assigned to x, but how can it have two =s?

Chris Smith
  • 2,928
  • 4
  • 27
  • 59

3 Answers3

7

x = 1 both assigns the value 1 to x and also 'returns' 1, it allows for things like this:

while ((line = reader.readLine()) != null)
Karrde
  • 471
  • 2
  • 9
  • P.S. In java, that sort of thing is considered a code smell in most situations - the only time it's sometimes OK (depends on who you talk to) is similar to the example above – Karrde Jun 11 '15 at 13:58
3

Read assignment statement from right to left:

Acording to Assignment Operators

There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

So,

int x = x = 1; 

is the same as

x = (x = 1); 

then

x = 1; x = x;
Jorge Casariego
  • 21,948
  • 6
  • 90
  • 97
1

int x puts x on the stack.

The right hand part x = 1 assigns 1 to x. But this is an expression with value 1.

Finally this is re-assigned to x.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483