Static blocks in Java

Course Curriculum

Static blocks in Java

Static blocks in Java

Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time the class is loaded into memory. For example, check output of following Java program.

// filename: Main.java
class Test{
static int i;
int j;

// start of static block
static {
i = 98;
System.out.println("Called Static Block ");
}
// end of static block
}

class Main {
public static void main(String args[]) {

// Although we don't have an object of Test, static block is
// called because i is being accessed in following statement.
System.out.println(Test.i);
}
}
Output:
Called Static Block
98

Also, static blocks are executed before constructors. For example, check output of following Java program.

// filename: Main.java
class Test {
static int i;
int j;
static {
i = 10;
System.out.println("Called Static Block ");
}
Test(){
System.out.println("Constructor called");
}
}

class Main {
public static void main(String args[]) {

// Although we have two objects, static block is executed only once.
Test t1 = new Test();
Test t2 = new Test();
}
}
Output:
static block called
Constructor called
Constructor called

What if we want to execute some code for every object?
We use Initializer Block in Java

Instance Variable Hiding in Java (Prev Lesson)
(Next Lesson) The Initializer Block in Java
', { 'anonymize_ip': true });