-3

In the code below why is the initializer block not called? But if the main() is removed from this class and when it is loaded from another class, the initializer block executes.

public class AAStatic {
static String s = "a";

{
    System.out.println("hi");
    m1();
}
public static void main(String[] args) {
    m1();
    System.out.println(s);
}

static{
    m1();
}
static void m1(){
    s+="b";
}
}

2 Answers2

1

Because you do not create any instance of AAStatic class. Initializer block is executed before constructor code (even if you do not write explicit constructor implicit constructor generated).

You can add static to your initializer then it will be executed when class is loaded.

talex
  • 17,973
  • 3
  • 29
  • 66
1

There are two types of initializer blocks.

The one with statc is Static Initialization Blocks

static{
   m1();
}

So it will be called the first time you use that class so that it can be used to initialize your class.

The one without static is to initialize instance. Thus, you do not create any instances of AAStatic will not call that block. Try:

public static void main(String[] args) {
    new AAStatic();//new instance here
    m1();
    System.out.println(s);
}

ref:

Community
  • 1
  • 1
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149