Site icon Experiences Unlimited

Initialization Blocks in Java

Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed. Initialization Blocks come in two flavours:

Code Snippet:

class InitDemo
{

static int y;
int x;
//Static Initialization Block
static
{

y=10;

}
// Instance Initialisation Block
{

x=20;

}

}

Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run. The order in which initialization blocks appear in a class matters. If a class has more than one they all run in the order they appear in the class file.

Some rules to remember:

“Hello World” program in Java without ever using a main method-

public class Hello
{

//Static Initialisation Block
static
{

System.out.println(“Hello, World“);
System.exit(0);

}

}

Exit mobile version