michal michal - 1 year ago 83
Java Question

Is the class loaded when it's 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(){
return 0;
static final int i = f();
public class Main {
public static void main(String[] args) {
A a;

The code gives no output.

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download