Static Blocks
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 17 of 87.
Sometimes you need to initialize static variables with logic that's more complex than a simple assignment. A static block (also called a static initializer) runs once when the class is first loaded, before any objects are created or static methods are called.
public class DatabaseConfig {
private static String connectionString;
private static int maxConnections;
static {
// Complex initialization logic
connectionString = "jdbc:mysql://localhost:3306/mydb";
maxConnections = 10;
System.out.println("Database configuration loaded");
}
}The static block executes automatically when the class is loaded into memory. This happens only once, regardless of how many objects you create. It's perfect for initialization that requires multiple statements, calculations, or conditional logic.
You can have multiple static blocks in a class, and they execute in the order they appear:
public class AppSettings {
private static int[] values;
static {
values = new int[5];
}
static {
for (int i = 0; i < values.length; i++) {
values[i] = i * 10;
}
}
}Static blocks are commonly used for initializing static arrays or collections, setting up configuration values that require computation, and performing one-time setup tasks at the class level.
Challenge
EasyLet's build a GameConfig system that uses static blocks to initialize game settings when the class is first loaded. This is perfect for configuration that needs to be computed or set up once before any game objects are created.
You'll create two files to organize your code:
GameConfig.java: Create a configuration class that initializes its settings using static blocks:- A private static array
levelThresholds(int[]) that stores the score needed to reach each level - A private static variable
maxLevel(int) storing the total number of levels - A private static variable
configLoaded(boolean) to track if initialization happened - Use a static block to initialize
maxLevelto 5 and print"Initializing game configuration..." - Use a second static block to create the
levelThresholdsarray with size equal tomaxLevel, then fill it so each level requireslevel * 100points (level 1 needs 100, level 2 needs 200, etc.), and setconfigLoadedtotrue - A static method
getThreshold(int level)that returns the score threshold for that level (levels are 1-indexed) - A static method
getMaxLevel()that returns the maximum level - A static method
isConfigLoaded()that returns whether the config has been loaded
- A private static array
Main.java: Demonstrate that the static blocks run automatically when the class is accessed. You'll receive one input: a level number to query. Print four lines:Config loaded: trueorConfig loaded: falseMax level: [maxLevel]Level [level] threshold: [threshold]Level 1 threshold: [threshold](always show level 1 as well)
You will receive one input: the level number (int) to query.
Notice how the initialization message prints before any of your Main code runs - that's the static block executing when the class is first loaded!
Cheat sheet
A static block (or static initializer) runs once when the class is first loaded, before any objects are created or static methods are called. It's used for complex initialization logic that requires multiple statements.
public class Example {
private static String value;
static {
// Initialization logic
value = "initialized";
System.out.println("Static block executed");
}
}Static blocks execute automatically when the class is loaded into memory, only once regardless of how many objects are created.
You can have multiple static blocks in a class. They execute in the order they appear:
public class Example {
private static int[] values;
static {
values = new int[5];
}
static {
for (int i = 0; i < values.length; i++) {
values[i] = i * 10;
}
}
}Common uses include initializing static arrays or collections, setting up configuration values that require computation, and performing one-time setup tasks at the class level.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int level = scanner.nextInt();
// TODO: Access GameConfig to demonstrate static block execution
// The static blocks in GameConfig will run automatically when you first access the class
// TODO: Print whether config is loaded
// Format: "Config loaded: true" or "Config loaded: false"
// TODO: Print the max level
// Format: "Max level: [maxLevel]"
// TODO: Print the threshold for the input level
// Format: "Level [level] threshold: [threshold]"
// TODO: Print the threshold for level 1
// Format: "Level 1 threshold: [threshold]"
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System