manikanta manikanta - 1 month ago 10
Java Question

Java - static assignment calling the method twice

Hmmm... I m not able to come up with a better title for this question

I m not able to understand why calling a static method and assigning it's value to another static member is calling the method

getValue()
twice.

If I move the static assignment after
main
method, it is not loading twice.
I know this is stupid, but am I missing something obvious?

public class Test {
private static Integer value1 = getValue(); // This is causing to load again

private static Integer flag = null;

public static Integer getValue() {
if (flag != null) { // if flag is loaded already, return it.
return flag;
}

System.out.println("Loading value...");

flag = Integer.valueOf(10);

return flag;
}

public static void main(String[] args) {
getValue();
}

private static Integer value2 = getValue(); // This will not cause to load again
}


Output:

Loading value...
Loading value...


Test online: https://ideone.com/pgRbff

Answer

Let's step through a few key lines.

This line:

private static Integer value1 = getValue();

prints "Loading value..." and sets flag to a non-null value.

Then this line:

private static Integer flag = null;

sets flag back to null.

Then this line:

private static Integer value2 = getValue();

prints "Loading value..." again and sets flag to a non-null value again.

Then main runs, and this line:

getValue();

doesn't print anything, because flag is set to a non-null value.