Search code examples
javastatic-variables

Why does a static variable initialized by a method call that returns another static variable remains null?


I simply don't understand the following code's execution flow:

class Test {
    static String s1 = getVal();
    static String s2 = "S2";

    private static String getVal() {
        return s2;
    }

    public static void main(String args[]) {
        System.out.println(s2); // prints S2
        System.out.println(s1); // prints null
    }
}

It is supposed to print S2 at second println statement. I am more interested in understanding why this happens rather than a solution.


Solution

  • Static things gets executed in the order they appear in the code.

    static String s1 = getVal();
    

    So starting with first line, s1 gets evaluated and by that time s2 is still null. Hence you see the null value.