Java - What is the output: Class initializer

Question

What is the output of the following code.

public class Main {

  static {
    System.out.println("Class initializer 1.");
  }

  static private int a = 1;

  static {
    System.out.println("Class initializer 2.");
    System.out.println(a);
    a = 2;
  }

  {
    System.out.println("Instance initializer 1.");
    System.out.println(b = 2);
  }

  int b = 1;

  {
    System.out.println("Instance initializer 2.");
    System.out.println(b);
    b = 3;
  }

  Main() {
    System.out.println("Constructor.");
  }

  public static void main(String[] args) {
    System.out.println(a);

    System.out.println(new Main().b);
  }
}


Click to view the answer

Class initializer 1.
Class initializer 2.
1
2
Instance initializer 1.
2
Instance initializer 2.
1
Constructor.
3

Demo

public class Main {

  static {//from   w ww. ja va2s.  c  o m
    System.out.println("Class initializer 1.");
  }

  static private int a = 1;

  static {
    System.out.println("Class initializer 2.");
    System.out.println(a);
    a = 2;
  }

  {
    System.out.println("Instance initializer 1.");
    System.out.println(b = 2);
  }

  int b = 1;

  {
    System.out.println("Instance initializer 2.");
    System.out.println(b);
    b = 3;
  }

  Main() {
    System.out.println("Constructor.");
  }

  public static void main(String[] args) {
    System.out.println(a);

    System.out.println(new Main().b);
  }
}

Related Topic