user2469133
user2469133

Reputation: 1970

Java Initialize Variable Incremented

Is it risky 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 compiler could read a global value before the other?

Upvotes: 3

Views: 1291

Answers (2)

talex
talex

Reputation: 20542

Result will be a=3, b=0, c=1, d=2.

If all this variable declared in one class they will be initialized in order of occurrence in code.

PS: b = 0 because a++ get value and then increment variable.

Upvotes: 3

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

It will behave as expected. If you try to use a field before it's defined, the compiler will throw an error:

public class Foo {
    int a = b++; //compiler error here
    int b = 0;
}

This is covered in JLS 8.3

For your case, the output of the variables if they're not modified, would be:

a = 3
b = 0
c = 1
d = 2

Upvotes: 4

Related Questions