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?

+3


source to share


2 answers


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

      

+4


source


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.

+3


source







All Articles