In method or class scope, the line below compiles (with warning):
int x = x = 1;
In class scope, where variables get their default valu
The line of code does not compile with a warning because of how the code actually works.
When you run the code int x = x = 1
, Java first creates the variable x
, as defined. Then it runs the assignment code (x = 1
). Since x
is already defined, the system has no errors setting x
to 1. This returns the value 1, because that is now the value of x
. Therefor, x
is now finally set as 1.
Java basically executes the code as if it was this:
int x;
x = (x = 1); // (x = 1) returns 1 so there is no error
However, in your second piece of code, int x = x + 1
, the + 1
statement requires x
to be defined, which by then it is not. Since assignment statements always mean the code to the right of the =
is run first, the code will fail because x
is undefined. Java would run the code like this:
int x;
x = x + 1; // this line causes the error because `x` is undefined