0

Might be a silly question, but when is the static variable initialized(so it occupies memory) while the program is running?

public class TestStaicInitilization {
    int i;
    public static final TestStaicInitilization test = new TestStaicInitilization();
    TestStaicInitilization(){
        this.i = 10;
    }
    public static void main(String[] args) {
       System.out.println(TestStaicInitilization.test.i);
    }
}

the output is: 10

Is the TestStaicInitilization.test initialized while loading the class itself or when it is first accessed?

Tom Sebastian
  • 3,373
  • 5
  • 29
  • 54
  • 2
    In the example you give, those two things are the same. The class is loaded when it is first accessed, and static initializers are run when the class is loaded. – dcsohl Aug 25 '15 at 13:58
  • I'm not certain, but I believe Java lazy-loads classes (ie. doesn't load them from file until code needed from them is invoked). After that point, the static initializers are run. I think someone more familiar with the JLS can answer that better, though. – Shotgun Ninja Aug 25 '15 at 13:59
  • Actually, class initialization is lazy too. See the linked Q&A. – Stephen C Aug 25 '15 at 14:00
  • @dcsohl the static initializers also initialize static member variables? – Tom Sebastian Aug 25 '15 at 14:14
  • 1
    Yes, a static initializer is either a) an assignment of a `static` field, or b) a `static { ... }` code block in the class. So: the expression `TestStaicInitilization` is evaluated left-to-right, as is the norm. When you first refer to `TestStaicInitilization`, the JVM loads the class, which triggers the static initializers--at this point, `test` is created and assigned. So now you have `TestStaicInitilization.test` and can look at its `i`. – dcsohl Aug 25 '15 at 16:01

0 Answers0