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.
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:
public static void main(String[] args) {
A a = new A();
}
public static void main(String[] args) {
int f = A.f();
}