0
0
Javaprogramming~15 mins

Static blocks in Java

Choose your learning style8 modes available
menu_bookIntroduction

Static blocks run code once when the class loads. They help set up things before you use the class.

To initialize static variables with complex logic.
To run setup code once before any object is created.
To load configuration or resources when the program starts.
To print a message or log when the class is first used.
regular_expressionSyntax
Java
static {
    // code to run once when class loads
}

Static blocks run only once, when the class is loaded by the Java Virtual Machine.

You can have multiple static blocks; they run in the order they appear.

emoji_objectsExamples
line_end_arrow_notchThis static block prints a message when the class loads.
Java
class Example {
    static {
        System.out.println("Static block runs");
    }
}
line_end_arrow_notchThis static block sets a static variable with a calculation.
Java
class Example {
    static int value;
    static {
        value = 10 * 2;
    }
}
line_end_arrow_notchMultiple static blocks run in order when the class loads.
Java
class Example {
    static {
        System.out.println("First block");
    }
    static {
        System.out.println("Second block");
    }
}
code_blocksSample Program

This program shows a static block that runs once before main. It sets the static variable number. The main method then prints the value.

Java
public class StaticBlockDemo {
    static int number;
    static {
        System.out.println("Static block is running");
        number = 5 * 5;
    }
    public static void main(String[] args) {
        System.out.println("Number is: " + number);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Static blocks cannot access instance variables directly because they run before any object exists.

line_end_arrow_notch

If you have multiple static blocks, they run top to bottom in the class.

line_end_arrow_notch

Static blocks are useful for one-time setup related to the class itself.

list_alt_checkSummary

Static blocks run once when the class loads.

They are used to initialize static variables or run setup code.

Multiple static blocks run in the order they appear.