manikanta
manikanta

Reputation: 8500

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

Upvotes: 2

Views: 1229

Answers (2)

Avdhesh Yadav
Avdhesh Yadav

Reputation: 33

This is good question. Classloader follow some rule to load a class, static statements load first and create memory for that at class area in heap memory.

Upvotes: -2

user2357112
user2357112

Reputation: 280838

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.

Upvotes: 7

Related Questions