Search code examples
javaclassreferenceinitializationloading

Is the class loaded when its reference is declared?


Does creating a reference to an object of a class cause the class to be loaded?

Static variables are initialized when the class is loaded, so considering the following code the answer is no, am I right?

    class A{
        static int f(){
            System.out.println("initializing!");
            return 0;
        }
        static final int i = f();
    }
    public class Main {
        public static void main(String[] args) {
            A a;
        }
    }

The code doesn't give any output.


Solution

  • Yes. Static initializers are called when a class method is called or an instance is instantiated.

    From your example you can do one of the following:

    1. Create New Instance

    public static void main(String[] args) {
        A a = new A();
    }
    

    2. Call Static Class Method

    public static void main(String[] args) {
        int f = A.f();
    }