Java Initialize Variable Extension
Is it possible to initialize a global variable with an increment of another global variable?
Example:
int a=0;
int b=a++;
int c=a++;
int d=a++;
This should output:
0,1,2,3
Could it happen that the compiler could read the global value before another?
It will behave as expected. If you try to use a field before defining it, the compiler throws an error:
public class Foo {
int a = b++; //compiler error here
int b = 0;
}
This is documented in JLS 8.3
In your case, the output of the variables, if not changed, would be:
a = 3
b = 0
c = 1
d = 2
The result will be a=3, b=0, c=1, d=2
.
If all this variable, declared in the same class, will be initialized in the order of appearance in the code.
PS: b = 0
because it a++
gets the value and then increments the value of the variable.