Why use instance initializer block in Java?

JavaJava Programming Java 8

instance initializer block is similar to a constructor. It is called once for each object and can be used to set initial values for instance variables. See the example below.

Live Demo

public class Tester {
   public int a;
   { a = 10; }
   public static void main(String[] args) {
     System.out.println(new Tester().a);
It will print the value of an as 10.

Published on 23-Apr-2018 11:45:37