Static Block Syntax and Placement
What you'll learn: How to write static initialization blocks and where to position them in your class.
Now that you know what static blocks are, let's look at the exact syntax for writing them and the rules for where they can appear in your code.
The Syntax
A static block begins with the keyword static followed by a pair of curly braces containing statements:
static {
// initialization code here
}
That's it! No method name, no return type, no parameters—just static and a block of code.
Where Static Blocks Can Go
Static blocks must appear inside a class definition, at the class level (not inside methods or constructors). You can place them:
- Before fields
- After fields
- Between field declarations
- Before or after methods
- Before or after constructors
public class Example {
static int count;
static {
count = 100; // Valid here
}
private String name;
static {
// Another static block - also valid!
}
public Example() {
// Constructor
}
}
Multiple Static Blocks
You can have multiple static blocks in a single class. They execute in the order they appear, from top to bottom, along with any field initializations.
Think of it like this: Static blocks are like setup instructions that run once when the class is first loaded—like a checklist the JVM works through before the class is ready to use.
Key Takeaway: Static blocks use the syntax static { ... }, must be placed at the class level (not inside methods), and can appear anywhere among your field and method declarations. Multiple static blocks execute in top-to-bottom order.