Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to perform static and instance initialization in Java

Anjana Shankar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Static initialization

Typically, static initialization is used to initialize static variables of a class. The block is called at the time of class initialization. It is called only once.

You can initialize static variables inline.

If more complicated logic is required for initialization, a static initialization block can be used. The static initialization blocks are called in the order in which they occur, and they are called before the constructors.

Code

class StaticTest {
static int i;
static {
System.out.println("Static Initialization block is called");
i = 10;
}
StaticTest() {
System.out.println("Static Test Constructor is called");
}
}
class Main {
public static void main (String args[]){
System.out.println(StaticTest.i);
}
}
Static Initializaton

Instance initialization

The instance initialization or initializer block is called whenever an instance of the class is created. It can be used to execute code that is common to all constructors. This block is executed before the constructor is executed.

Code

class InitializerTest {
int i;
{
System.out.println("Instance Initialization block is called");
i = 5;
}
InitializerTest() {
System.out.println("Initializer Test Default Constructor is called");
}
InitializerTest(int x) {
System.out.println("Initializer Test Parametrized Constructor is called");
i = x;
}
}
class Main {
public static void main (String args[]){
InitializerTest obj1 = new InitializerTest();
System.out.println(obj1.i);
InitializerTest obj2 = new InitializerTest(10);;
System.out.println(obj2.i);
}
}
Instance Initialization

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring