Why does this Java code compile?


int x = x = 1;

is equivalent to

int x = 1;
x = x; //warning here

while in

int x = x + 1; 

first we need to compute x+1 but the value of x is not known so you get an error (the compiler knows that the value of x is not known)


In method or class scope, the line below compiles (with warning):

int x = x = 1;

In class scope, where variables get their default values, the following gives 'undefined reference' error:

int x = x + 1;

Isn't it the first x = x = 1 should end up with same 'undefined reference' error? Or maybe the second line int x = x + 1 should compile? Or there is something I am missing?

Complier read statements from right to left and we designed to do the opposite. That's why it annoyed at first. Make this a habbit to read statements (code) from right to left you won't have such problem.

The second one int x=x=1 is compile because you are assigning the value to the x but in other case int x=x+1 here the variable x is not initialized , Remember in java local variable are not initialized to default value. Note If it's (int x=x+1) in class scope also then also it will give compilation error as the variable is not created.

In the second piece of code, x is used before its declaration, while in the the first piece of code it is just assigned twice which doesn't make sense but is valid.

In int x = x + 1; you add 1 to x , so what is the value of x, it's not created yet.

But in int x=x=1; will compile with no error because you assign 1 to x.

x is not initialised in x = x + 1;.

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used.

See primitive data types

In java or in any modern language, assignment comes from the right.

Suppose if you are having two variables x and y,

int z = x = y = 5;

This statement is valid and this is how the compiler splits them.

y = 5;
x = y;
z = x; // which will be 5

But in your case

int x = x + 1;

The compiler gave an exception because, it splits like this.

x = 1; // oops, it isn't declared because assignment comes from the right.