devxlogo

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

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist