Static Blocks In Class

Static Blocks In Class

A school program needs reliable data and clear rules. A static initializer prepares class-level state when the class is initialized. It is useful when a shared value needs more than a simple initializer.

  1. Understand

    A static initializer prepares class-level state when the class is initialized.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Class initialization is not repeated for each new object. Avoid expensive or surprising external work in initializers.

What is a Static Block in Java?

In Java, a static block (also known as a static initialization block) is a code block that's executed once when the class is loaded into memory. It's mostly used to initialize static variables or execute code that must run before any objects of the class are created.

Why Use a Static Block?

Static blocks are especially useful when:

  • You need to perform complex static variable initialization.
  • You want to run code at class loading time – like reading configuration or logging setup.
  • You want something to execute even before the main method is called.

Syntax of a Static Block

class MyClass {
    static {
        // This code runs once when the class is loaded
    }
}

Example 1: Basic Static Block Execution

public class StaticBlockExample {
    static {
        System.out.println("Static block executed");
    }

    public static void main(String[] args) {
        System.out.println("Main method executed");
    }
}
Static block executed
Main method executed

Explanation:

Java · example discussed here

public class StaticBlockExample {
    static {
        System.out.println("Static block executed");
    }

    public static void main(String[] args) {
        System.out.println("Main method executed");
    }
}

When you run the class, the JVM loads it and executes the static block first. After that, it invokes the main() method.

Example 2: Initializing Static Variables

public class Config {
    static int MAX_USERS;
    static String APP_NAME;

    static {
        MAX_USERS = 100;
        APP_NAME = "MyApp";
        System.out.println("Static block: Configuration loaded");
    }

    public static void main(String[] args) {
        System.out.println("App: " + APP_NAME);
        System.out.println("Max users: " + MAX_USERS);
    }
}
Static block: Configuration loaded
App: MyApp
Max users: 100

Explanation:

Java · example discussed here

public class Config {
    static int MAX_USERS;
    static String APP_NAME;

    static {
        MAX_USERS = 100;
        APP_NAME = "MyApp";
        System.out.println("Static block: Configuration loaded");
    }

    public static void main(String[] args) {
        System.out.println("App: " + APP_NAME);
        System.out.println("Max users: " + MAX_USERS);
    }
}

The static block sets up configuration data for the class. It's run only once and the values are available for use throughout the application wherever static members are accessible.

Example 3: Multiple Static Blocks

public class MultiStaticBlocks {
    static {
        System.out.println("Static block 1");
    }

    static {
        System.out.println("Static block 2");
    }

    public static void main(String[] args) {
        System.out.println("Main method");
    }
}
Static block 1
Static block 2
Main method

Explanation:

Java · example discussed here

public class MultiStaticBlocks {
    static {
        System.out.println("Static block 1");
    }

    static {
        System.out.println("Static block 2");
    }

    public static void main(String[] args) {
        System.out.println("Main method");
    }
}

If there are multiple static blocks, they execute in the order they appear in the class, from top to bottom, during class loading.

Example 4: No Object Required

public class NoObjectNeeded {
    static {
        System.out.println("Class is loaded!");
    }

    public static void hello() {
        System.out.println("Hello!");
    }
}
// Another class
public class Test {
    public static void main(String[] args) {
        NoObjectNeeded.hello();
    }
}
Class is loaded!
Hello!

Explanation:

Java · example discussed here

// Another class
public class Test {
    public static void main(String[] args) {
        NoObjectNeeded.hello();
    }
}

Even though we didn’t create an object of NoObjectNeeded, calling its static method triggered class loading, which caused the static block to run. Static blocks belong to the class itself, not to any instance.

Points to Remember

  • Static blocks run once, at class loading time.
  • You can have multiple static blocks – they'll execute in order.
  • Used for static variable initialization, logging setup, etc.
  • Runs even before main() if the class is loaded.

Common Use Cases

  • Initializing database connections (not recommended for production but okay for demos).
  • Loading configuration from files.
  • Static logging setup or metrics initialization.

Interview Tip

Static blocks are a common favorite in Java interviews. You might be asked, "What happens if there's a static block but no main method?" Answer: the static block still runs when the class is loaded, but you'll get a runtime error unless a valid main() method is found to continue execution.

Conclusion

Static blocks might feel like backstage workers in Java – quiet, behind the scenes, but essential. Whether you're preloading values or just setting the stage before the curtain rises (a.k.a. main()), understanding static blocks is a fundamental step toward mastering class behavior and lifecycle in Java.

Important boundaries and mistakes

Class initialization is not repeated for each new object. Avoid expensive or surprising external work in initializers.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Class initialization is not repeated for each new object.

Java 17 · Main.java · complete practice program

public class Main  {
  static class School  {
    static String name;
    static  {
      System.out.println("Initializing");
      name = "River School";
    }
  }
  public static void main(String[] args)  {
    System.out.println(School.name);
    System.out.println(School.name);
  }
}

Now change one thing: Read School.name a third time. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  static class School  {
    static String name;
    static  {
      System.out.println("Initializing");
      name = "River School";
    }
  }
  public static void main(String[] args)  {
    System.out.println(School.name);
    System.out.println(School.name);
  }
}

Expected output

Initializing
River School
River School

A static initializer prepares class-level state when the class is initialized. It is useful when a shared value needs more than a simple initializer.

Class initialization is not repeated for each new object. Avoid expensive or surprising external work in initializers.

Run with javac Main.java, then java Main. The declaration inside Main keeps the helper type available to this standalone example.

Worked variation: Read School.name a third time. The initialization message still appears only once.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Initializing River School River School

A static initializer prepares class-level state when the class is initialized. It is useful when a shared value needs more than a simple initializer. Class initialization is not repeated for each new object. Avoid expensive or surprising external work in initializers.

What to remember

A static initializer prepares class-level state when the class is initialized. It is useful when a shared value needs more than a simple initializer. Class initialization is not repeated for each new object. Avoid expensive or surprising external work in initializers.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Final Variables →