michal michal - 3 months ago 15
Java Question

Is the class loaded when it's been instantiated?

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 gives no output.

Answer

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();
}
Comments