Sub topic 9
Static and instance initialization blocks
This chapter assumes you can declare Apex classes, write constructors, and tell static members from instance members. It covers two features that run setup code outside a constructor: static initialization blocks and instance initialization blocks.
What an initialization block is
An initialization block is a pair of braces placed directly in the class body, outside any method or constructor. Apex has two kinds:
- A static initialization block is preceded by the
statickeyword. It runs once per class, the first time the class is used in a transaction. - An instance initialization block has no keyword, just braces. It runs every time an object is created with
new, before the constructor body.
public class Example {
static {
// static initialization block
}
{
// instance initialization block
}
}A class can contain any number of either kind. Blocks and field initializers run in the order they appear in the file.
Static initialization blocks
Chapter 8 showed that a static final variable can be assigned in its declaration. That only works when one expression is enough. A static block lets you use loops, several statements, and local variables to build the value.
public class Priority {
public static final Map<String, Integer> RANK;
static {
RANK = new Map<String, Integer>();
List<String> names = new List<String>{ 'Low', 'Medium', 'High' };
for (Integer i = 0; i < names.size(); i++) {
RANK.put(names[i], i);
}
}
}
// Usage
System.debug(Priority.RANK.get('High')); // 2The RANK variable is declared without a value. The compiler accepts this because a static final variable may be assigned exactly once, either in its declaration or in static initialization code. If you assign it twice, or assign it from a regular method, compilation fails.
The local variables names and i exist only inside the block. This is a useful side effect. A helper list that you need only during setup does not become a class member.
What a static block can touch
A static block follows the same rules as a static method. It can read and write static members. It cannot use this or reference instance variables, because no object exists when it runs.
When it runs
The block runs when the class is first loaded in a transaction. Loading happens on the first of these events: calling a static method, reading a static variable, or creating an instance. It does not run again in the same transaction. The next transaction starts with a fresh copy, so the block runs again there. This is the same lifetime as every other static variable, covered earlier in this tutorial.
Instance initialization blocks
An instance block runs for every new object. Its main use is setup code that every constructor needs.
public class Report {
public final Datetime createdOn;
private List<String> rows;
{
createdOn = Datetime.now();
rows = new List<String>();
}
public Report() {
rows.add('Untitled');
}
public Report(String firstRow) {
rows.add(firstRow);
}
public Integer size() {
return rows.size();
}
}
// Usage
Report r = new Report('Q4 totals');
System.debug(r.size()); // 1Both constructors receive a ready rows list and a createdOn timestamp. Neither constructor repeats that setup. A final instance variable can be assigned in its declaration, in an instance block, or in a constructor. It cannot be assigned anywhere else.
Do you need one?
Often not. If the setup is a single expression, a field initializer is shorter and easier to read:
private List<String> rows = new List<String>();Use an instance block when the setup takes several statements and more than one constructor needs it. If only one constructor needs it, put the code in that constructor.
Order of execution
The most common source of confusion is the order in which things run. The following class records each step into a log, so you can see it.
public class InitOrder {
public static String log = '';
public static Integer a = record('static field a');
static {
record('static block');
}
public static Integer b = record('static field b');
private Integer x = record('instance field x');
{
record('instance block');
}
public InitOrder() {
record('constructor');
}
private static Integer record(String step) {
log += step + '\n';
return log.length();
}
}
// Usage
new InitOrder();
new InitOrder();
System.debug(InitOrder.log);The debug output is:
static field a
static block
static field b
instance field x
instance block
constructor
instance field x
instance block
constructorThree things stand out:
- The static items run once, in file order, before the first object is built.
- For each object, field initializers and instance blocks run in file order, and the constructor body runs last.
- The second
new InitOrder()skips the static items entirely.
Because order depends on position in the file, moving a block can change behavior. If an instance block reads a field that is declared below it, that field has not been initialized yet and still holds null. Declare fields before the blocks that use them.
Comparing the options
| Feature | Static block | Instance block | Constructor |
|---|---|---|---|
| Runs | Once per class per transaction | Once per object | Once per object |
| Runs before | The first use of the class | The constructor body | Nothing else for that object |
| Can use `this` | No | Yes | Yes |
| Can assign `static final` | Yes | No | No |
| Can assign instance `final` | No | Yes | Yes |
| Can take parameters | No | No | Yes |
The last row explains why blocks are limited. Anything that depends on the caller's input belongs in a constructor.
Failure modes and gotchas
Governor limits
A static block runs inside the transaction, so its cost counts against that transaction's limits. A SOQL query in a static block uses one of the 100 synchronous queries every time the class loads. This is true even if the calling code never needed the result. For expensive data, prefer lazy loading with a static method:
public class RecordTypeCache {
private static Map<String, Id> idsByName;
public static Id idFor(String developerName) {
if (idsByName == null) {
idsByName = new Map<String, Id>();
for (RecordType rt : [SELECT Id, DeveloperName FROM RecordType]) {
idsByName.put(rt.DeveloperName, rt.Id);
}
}
return idsByName.get(developerName);
}
}The query runs only on the first call, and only if someone calls the method.
Errors during initialization
If code in a static block throws an exception, the class cannot finish loading. The failure surfaces in whatever code first touched the class, which can be far from the block that caused it. Keep static blocks short and free of operations that can fail, such as queries, callouts, or DML.
Hidden dependencies between classes
If class A's static block uses class B, and class B's static block uses class A, you get a circular dependency that is hard to reason about. Avoid it by keeping static blocks self-contained.
Hard-to-read order
Mixing many blocks and field initializers through a long class makes execution order hard to follow. A good habit is to group all static declarations and blocks at the top of the class, then instance fields and blocks, then constructors.
Choosing between the options
- Use a field initializer for a single-expression default.
- Use a static block to build a
static finalvalue that needs several statements. - Use an instance block for multi-statement setup shared by several constructors, or to assign an instance
finalvariable in one place. - Use a constructor for anything that depends on parameters.
- Use a lazy static method for anything costly or optional.
Exercise
A class declares public static final List<Integer> SQUARES; and a static block that fills it with the squares of 1 to 3. Your colleague moves the loop into a regular static method called init() and assigns SQUARES there. What happens, and why?
Show answer
The class fails to compile. A static final variable can be assigned only in its declaration or in static initialization code, so assigning it from a regular method is not allowed. The fix is to keep the assignment in a static block, or to assign SQUARES once in its declaration and have init() only add elements to the list.
Exercise
Given a class that declares, in this order, an instance block that logs 'block', a field Integer x = log('field'), and a constructor that logs 'ctor', what is the log after one new call?
Show answer
The log is 'block', 'field', 'ctor'. Instance blocks and field initializers run in file order, and the constructor body runs last. The block comes first because it appears first in the file.