-2

I have a Java class:

Class A {
  static Object a = new Object();
  Object getObject() {
    return a;
  }
}

In above code. I want to ask when object a is really initialized. I have two answers for my question:

  1. When Java program is started. a will automatically initialize, although we will never use it.

  2. the very first time we call getObject(). So, I think this will be more optimize.

I don't know which really true behind the scene.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107

1 Answers1

2

When the JVM loads class A, it executes "static" block of code and initializes static variables as well.

suman j
  • 6,710
  • 11
  • 58
  • 109