When the class loads, the static block runs once to initialize static variables before any object is created or main runs.
code_blocksExecution Sample
Java
class Test {
staticint x;
static {
x = 5;
System.out.println("Static block runs");
}
publicstaticvoid main(String[] args) {
System.out.println(x);
}
}
This code runs the static block once when the class loads, sets x to 5, then prints x in main.
data_tableExecution Table
Step
Action
Static Variable x
Output
1
Class loads, static variables initialized
0
2
Static block runs, sets x to 5
5
Static block runs
3
Main method starts, print x
5
5
4
Program ends
5
💡 Program ends after main method finishes
search_insightsVariable Tracker
Variable
Start
After Static Block
After Main
x
0 (default)
5
5
keyKey Moments - 3 Insights
▶Why does the static block run before main?
▶Does the static block run again if we create objects?
▶What is the initial value of static int x before the static block?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after the static block runs?
A0
BUndefined
C5
D10
photo_cameraConcept Snapshot
Static blocks run once when the class loads.
They initialize static variables.
Run before main or any object creation.
Syntax: static { /* code */ }
Useful for setup tasks.
Runs only once per class load.
contractFull Transcript
Static blocks in Java run once when the class is loaded by the JVM. This happens before the main method starts or any objects are created. In the example, the static block sets the static variable x to 5 and prints a message. The variable x starts with a default value of 0, then changes to 5 after the static block runs. The main method then prints the value of x. Static blocks are useful to initialize static variables or run setup code. They do not run again if multiple objects are created.