0

Suppose there is a static block in a Class

public class Menu {

    private static Map<String, String> buttonEventMap = new HashMap<String, String>();

    static {
        buttonEventMap.put("show-user","show");
        buttonEventMap.put("delete-user","delete");
    }

    public static Map<String, String> getHashMap() // To get the hash map
}

what is the life cycle of the block, when it will be instantiated, when the program starts or when we create the first object of the Class

dacwe
  • 42,413
  • 12
  • 112
  • 138
Isuru
  • 7,435
  • 8
  • 29
  • 38

2 Answers2

6

It's executed when the class is initialized by the class loader. And the class is initialized lazily, the first time some code in the application needs this class (to call a static method, or to reference one of its static fields, or to create a new instance for example).

So if the program never uses the class, the static block will never be executed.

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
  • 1
    A fully precise statement is that it's executed when the class is **initialized**. Class loading can occur at any time the implementation sees fit, whereas class init must happen at the precise moment defined by the JLS. – Marko Topolnik May 29 '12 at 09:37
2

When you first access the class in your application.

Jouni Aro
  • 2,011
  • 13
  • 28