We have just discussed how constructors are used to initialize the instance variables of a class. But how do you initialize class (static) variables? Class variables can be initialized either when they are declared or by using a static initialization block. This is simply a block of code preceded by the static keyword. static { // body of static initialization block } A static initialization block is not explicitly called. It is executed one time by the system when the class is first loaded. Example: Using Static Initialization BlocksThis simple example shows how a static initialization block provides an initial value for a class variable. The main() method never actually calls the static initialization block. The block is called by the system when the class is loaded. public class StaticInitDemo { public static int MAX_ITERATIONS; static { MAX_ITERATIONS = 50; } public static void main(String args[]) { System.out.println("MAX_ITERATIONS = "+ MAX_ITERATIONS); } } Output ” MAX_ITERATIONS = 50 |