Question

I have a class:

public class Foo {
    public static boolean flag = false;
    //some code
}

I am using this boolean flag in another class:

public class FooImpl{
    public static void main (String args[]) {
        if (Foo.flag){
            //Line 1
            //some code
        }
    }
}

So at Line 1, does class Foo gets fully loaded in the memory or just the static variable gets loaded with default value?

Was it helpful?

Solution

A classes static initialization normally happens immediately before the first time one of the following events occurs:

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or

See JLS 12.4.1.

OTHER TIPS

The class gets loaded when there is a static reference to the class. It is loaded by ClassLoader [java.lang.ClassLoader].

when you access a class member or constructor [creating an instance of that class] you need information about the class and it gets loaded.

you might have seen some ClassNotFoundException for some library function calls. The ClassLoader is behind that.

But there is other fact that the class gets initialized when something in the class is used first.

Initialization of a class consists of executing its static initializers and the initializers

for static fields (class variables) declared in the class.

In line 1 you are referring to a member of class and its loaded for sure.

Initialization Occurs:

T is a class and an instance of T is created.

  • T is a class and a static method declared by T is invoked.
  • static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable
  • T is a top level class, and an assert statement lexically nested within T is executed.

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top