-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
  • 83,472
  • 15
  • 149
  • 315
Trần Kim Dự
  • 5,572
  • 8
  • 44
  • 96

1 Answers1

2

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

suman j
  • 6,140
  • 10
  • 51
  • 99