Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Initialize Variable Incremented

Tags:

java

increment

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?

like image 223
user2469133 Avatar asked Jul 28 '26 19:07

user2469133


2 Answers

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
like image 76
Luiggi Mendoza Avatar answered Jul 30 '26 08:07

Luiggi Mendoza


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.

like image 23
talex Avatar answered Jul 30 '26 08:07

talex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!