views:

102

answers:

4

Quick question -

When are static fields initialized? If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant?

What if I call a static method? Does it also run all the static blocks? Before the method?

+1  A: 

Yes, all static initializers are run before you access class first time. If it was any other way, I would call it a bug.

Nikita Rybak
+1  A: 

back to the source!!! http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

Aaron Saunders
I've read all the tutorials, they aren't detailed enough. Stephen C's link was what I needed. Also naikus.
Tony R
A: 

Static fields are initialized during the initialization "phase" of the class loading (loading, linking and initialization) that includes static initializers and initializations of its static fields. The static initializers are executed in a textual order as defined in the class.

Consider the example:

public class Test {

   static String sayHello()  {
      return a;
   }

   static String b = sayHello(); // a static method is called to assign value to b.
                                 // but its a has not been initialized yet.

   static String a = "hello";

   static String c = sayHello(); // assignes "hello" to variable c

    public static void main(String[] arg) throws Throwable {
         System.out.println(Test.b); // prints null
         System.out.println(Test.sayHello()); // prints "hello"
    }
}

The Test.b prints null because when the sayHello was called in static scope, the static variable a was not initialized.

naikus
Strictly speaking, initialization is not a "phase" of class loading. Indeed, some classes *may* be loaded but never initialized if the application doesn't actually make use of them.
Stephen C
@Stephen C You are right, I used it for a lack of a better term, maybe i'll quote it.
naikus
+4  A: 

A classes static initialization normally happens immediately before the first time one of the following events occurs:

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or
  • for a top-level class, an assert statement lexically nested within the class is executed.

See JLS 12.4.1.

It is also possible to force a class to initialize (if it hasn't already initialized) by using Class.forName(String, boolean, ClassLoader).

Stephen C
Cool thanks for the extra info.
Tony R