Java Static Blocks
Table of Contents + −
In the last lesson you learned about Java static methods. Now picture a static variable that needs more than a one-line value to set up, like a lookup table built with a loop. Java has a special spot for that setup code, called a static block. Let’s learn it.
🤔 Why do we need a static block?
Some static variables are easy to set up. A simple value on the same line does the job.
static int maxUsers = 100;static String appName = "FreeCodingSchool";That works because the value is one expression. But sometimes the setup needs more:
- A static array filled with the first ten square numbers needs a loop to build it.
- A loop is several statements, and you cannot drop loose statements into a class body.
- A static block gives you a place for that setup code, and it runs automatically at class load.
- You never call it and never wire it to a constructor. Java runs it for you, once, at the right moment.
🧩 What is a static block?
A static block is code wrapped in static { ... } inside a class, outside any method. Java runs it once, when the class is first loaded, before any object is created or any static member is used. This snippet shows where it sits.
public class Settings {
static int maxUsers; // a static variable
static { // a static block maxUsers = 100; System.out.println("static block ran"); }}The block has no name, no return type, no parameters. Just static followed by braces. Java runs it automatically the first time the class is touched, like the class setting itself up before anyone uses it.
💡 Filling a static array with a static block
Let’s solve the square-numbers problem. A loop builds the array, and the static block is where the loop lives. This program fills the array at class load, then prints part of it from main.
public class Squares {
static int[] table = new int[10];
static { for (int i = 0; i < table.length; i++) { table[i] = i * i; } System.out.println("table filled"); }
public static void main(String[] args) { System.out.println("main started"); System.out.println("table[5] is " + table[5]); }}Walk through it:
- The static block loops over
tableand stores each square. - Java loads the
Squaresclass before runningmain. Loading it runs the static block, sotablefills first. - Then
mainreadstable[5], which is already set.
Output
table filledmain startedtable[5] is 25“table filled” prints before “main started”. That proves the static block ran during class load, before main.
🔢 Proving it runs once at load time
A static block runs once, when the class first loads. Making many objects does not run it again. This demo creates three objects and prints in both the static block and the constructor.
public class Widget {
static { System.out.println("STATIC BLOCK (class load)"); }
Widget() { System.out.println("constructor (new object)"); }
public static void main(String[] args) { System.out.println("main started"); new Widget(); new Widget(); new Widget(); }}Walk through it:
- Loading
Widgetruns the static block one time. - Then
mainmakes three objects. Eachnew Widget()runs the constructor, so that line prints three times. - The static block line prints only once, no matter how many objects you make.
Output
STATIC BLOCK (class load)main startedconstructor (new object)constructor (new object)constructor (new object)The static block belongs to the class, so it runs when the class arrives. The constructor runs once per object.
🧠 Execution order at class load
When a class loads, static field initializers and static blocks run in source order, top to bottom. Java does not run all fields first. It walks down the file and runs each static piece as it meets it.
public class Order {
static int a = printAndReturn("field a", 1);
static { System.out.println("static block 1"); }
static int b = printAndReturn("field b", 2);
static { System.out.println("static block 2"); }
static int printAndReturn(String label, int value) { System.out.println(label); return value; }
public static void main(String[] args) { System.out.println("main started, a=" + a + " b=" + b); }}Read it top to bottom, because that is how Java runs it. a is set, then static block 1, then b, then static block 2. Only then does main start.
Output
field astatic block 1field bstatic block 2main started, a=1 b=2Notice “static block 1” printed before “field b” was set. If your block needs a static field, declare that field above the block, or it will not have its value yet.
🔀 Multiple static blocks
You can have more than one static block in a class:
- Java runs them in the order they appear, blended with any static field initializers between them.
- There is no separate “static block phase”. It is one top-to-bottom pass over the static parts.
- A later block can rely on what an earlier block did. An earlier block cannot rely on a later one.
Keep related setup together
Multiple static blocks are handy for grouping. One block could fill a lookup table, another could check that the table looks right. As long as the check comes after the fill in the source, it sees the finished table.
📦 Static block versus instance initializer block
A cousin of the static block is the instance initializer block. It looks the same but without static, just { ... } in the class body. The difference is when it runs:
- A static block runs once at class load.
- An instance block runs every time you create an object, just before the constructor body.
This program has both.
public class Compare {
static { System.out.println("static block - once at load"); }
{ System.out.println("instance block - per object"); }
Compare() { System.out.println("constructor body"); }
public static void main(String[] args) { System.out.println("main started"); new Compare(); new Compare(); }}Trace it. The static block runs once at class load. Each new Compare() runs the instance block first, then the constructor body, so that pair prints twice.
Output
static block - once at loadmain startedinstance block - per objectconstructor bodyinstance block - per objectconstructor bodyThe rule is short. Static block: class-level setup, runs once. Instance block: object-level setup, runs per object.
⚠️ Common Mistakes
- Expecting it to run for every object. The static block runs once, at class load. If you need per-object setup, that belongs in the constructor or an instance block.
// ❌ Wrong idea: thinking this runs on each new Account()static { balance = 0; }
// ✅ Per-object setup goes in the constructorint balance;Account() { balance = 0; }- Doing heavy or slow work in a static block. The block runs while the class loads and blocks everything until it finishes. Reading a giant file here freezes the first use of the class.
// ❌ Slow work at class load delays the first use of the classstatic { loadHugeDatasetFromDisk(); }
// ✅ Load it lazily, only when something actually needs itstatic int[] data;static int[] getData() { if (data == null) data = loadHugeDatasetFromDisk(); return data;}- Assuming a field is ready before its line. Static parts run top to bottom. A block above a field cannot use that field’s value yet. Order your declarations so each block sees what it needs.
// ❌ This block runs before limit is set, so it reads 0static { System.out.println(limit); }static int limit = 50;
// ✅ Declare the field first, then use itstatic int limit = 50;static { System.out.println(limit); }- Hiding important logic with no obvious trigger. Nobody calls a static block, so people forget it exists. Surprising setup tucked in one is easy to miss when reading the class.
✅ Best Practices
- Use it only when a simple assignment will not do. If
static int x = 5;works, use that. Reach for a block when setup needs a loop or several steps. - Keep it fast. Class load should be quick. Move slow loading out and do it lazily, only when the data is first needed.
- Mind the order. Declare a static field before any block that uses it. Static parts run top to bottom.
- Group related setup. Multiple static blocks are fine for keeping related steps near each other. They run in source order.
- Comment the why. Because nobody calls a static block, a short comment saying what it sets up helps the next reader.
🧩 What You’ve Learned
- ✅ A static block is
static { ... }in the class body, outside any method. - ✅ It runs once, when the class is first loaded, before any object is created or any static member is used.
- ✅ It is the right place to set up static variables that need more than a simple assignment, like filling an array or map.
- ✅ Static field initializers and static blocks run in source order, top to bottom, before
mainin the same class. - ✅ You can have multiple static blocks, and they run in the order they appear.
- ✅ An instance initializer block looks similar but runs per object, not at class load.
- ✅ Avoid heavy work in a static block, and never expect it to run for each object.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
How many times does a static block run?
Why: A static block runs a single time, when the class is first loaded into memory.
- 2
When does a static block run relative to main, in the same class?
Why: Loading the class runs its static blocks first, so they finish before main starts.
- 3
In what order do static fields and static blocks run?
Why: Java makes one top-to-bottom pass, running each static field initializer and static block in source order.
- 4
What is the main difference between a static block and an instance initializer block?
Why: Static blocks set up the class once at load; instance blocks run each time an object is created.
🚀 What’s Next?
You now know how to set up static data when a class loads. Next, let’s look at a special kind of class built for a fixed set of named values, like days of the week or order states. They are called enums, and they make your code safer and clearer. Let’s learn them.