Why is my static block not being executed..

..when the class is loaded?

Start with an example from "Thinking in Java"..
class Candy {
    static { 
        System.out.println("Loading Candy"); 
class Gum {
    static { 
        System.out.println("Loading Gum"); 
class Cookie {
    static { 
        System.out.println("Loading Cookie"); 
public class SweetShop {
    public static void main(String[] args) {
        System.out.println("inside main");
        new Candy();
        System.out.println("After creating Candy");
        try {
        } catch(ClassNotFoundException e) {
            System.out.println("Couldn’t find Gum");
        System.out.println("After Class.forName(\"Gum\")");
        new Cookie();
        System.out.println("After creating Cookie");

and the output will be..
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie

There is no surprise here. And the explanation following this example is as follows..
Each of the classes Candy, Gum, and Cookie has a static clause that is executed as the class is loaded for the first time.
Not quite so..

Please see this thread in StackOverflow. Also this page is very useful as well.

To summarise..
Class Loading and Class Initialisation are 2 different things.
Static Initialisers are run only when a class is being initialised, NOT when a class is loaded.
A Class or Interface type T will be initialised immediately before the first occurrence of any one of the following:
  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable.
  • T is a top level class, and an assert statement lexically nested within T is executed.

Mystery solved!