Initializer Block

  • If a class contains some code just within curly braces{ }, it is known as the initializer block.
  • As soon as the object of a class is created, all constructors’ initializer block will get executed in sequence.
  • It is useful when the same code is to be written in all constructors.
  • Only one constructor will get executed so that the value will be assigned in all constructors. In contrast, all initializer blocks are executed so that the value will be assigned in only one initializer block.
  • The initializer block gets executed before the constructor.
  • It is not at all mandatory to include them in your classes.
public class Calculate {
	//Initializer block starts
	{
		System.out.println("Initializer block executed!!");
	}
	//Initializer block ends
	
	public Calculate() {
		System.out.println("Constructor executed!!");
	}
	public static void main(String args[]){
		Calculate caliculate = new Calculate();
	}
}



OUTPUT:
Initializer block executed!!
Constructor executed!!