Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Oct 8, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

How to Write Code that Doesn't Belong to any Method

In Java, a class can have zero or more blocks outside any methods that are labeled static and are surrounded by curly braces. These blocks, also known as static initializers, are executed only once, at the time the class is loaded. The following code shows this:
// StaticInitializerDemo1.java

/** Demonstrates static initializers. */
public class StaticInitializerDemo1 {

  static {
    System.out.println("Inside static initializer");


This code would compile, although it doesn't have main(). This is because main() is required by JVM to launch an application, but not the compiler. If you ran this program, the print statement in the static initializer would be executed, and the JVM would give an error since main() doesn't exist. The point being that a static initializer is executed at the time of class loading.

What happens if the code within the static initializer generates an exception?
import java.io.*;

/** Demonstrates static initializers. */
public class StaticInitializerDemo2 {

  static {
    int i = 1;
    System.out.println("Inside static initializer");
    // Purposely generate an exception
    if (i == 1) {
      throw new IllegalArgumentException("Error");

  /** Main. */
  public static void main(String[] args) {
    System.out.println("Inside main");


Here, we are initializing i to 1 in the static initializer and throwing an exception. Now, if an exception occurs while the static initializer is being executed, the class loading fails. This is why you should never have a code within a static initializer that can throw an exception.

If more than one static initializer is present in the class, they will be executed in the order they appear in the class. These are good enough for simple static initialization. However, avoid writing complex logic in them, especially if it can lead to exceptions.
Shantanu Garg
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date