When are init blocks called?

Consider this code:

public class Main {


 static String s = "-";

 public static void main (String [] args){

     go();
     System.out.println(s);

     Main m = new Main();
 }
 {go();}

 static {go();}
 static void go(){s+="s";}
}

      

Its conclusion:

-ss

      

the instance init block is never called, why?

+2


source to share


5 answers


It is called - AFTER you have typed s

. Instance initializers are called when instances are created.



+5


source


It is called. However, it gets called after the println call, because you are creating the first instance of Main. If you move the call to println to the end of main, you see three s.



+1


source


The instance initialization block code runs right after super () is called in the constructor, in other words, after all superconstructors have been run.

The order in which the initialization blocks appear in the class matters. If a class has more than one, they are all executed in the order in which they appear in the class file.

Some rules to remember:

  • List Item Initialization items are executed in the order in which they are displayed.
  • Static initialization blocks run once when the class is first loaded.
  • Instance initialization blocks run every time a class is instantiated.
  • Instance initialization blocks are run after the constructors are called super ().
+1


source


It gets called, but after printing to the console. You don't make a copy of it before printing. In the meantime, there is no need to worry about it.

0


source


As others have pointed out, the init block of the instance is called, but it does not affect the output of your statement System.out.println

, because it is called in conjunction with the call to an instance of your class:Main m = new Main();

One thing you could do when trying to debug these cases is to flush the thread stack at the point of the call:

static void go() {
    new Exception().printStackTrace(System.out);
        s += "s";
}

      

This will allow you to see all the time the method is called go

, and using the same print stream as yours println

in your method main

, you can see the stacks in relation to the output of your s

var.

In my version, the result looks like this:

java.lang.Exception
    at Main.go(Main.java:29)
    at Main.<clinit>(Main.java:25)
java.lang.Exception
    at Main.go(Main.java:29)
    at Main.main(Main.java:14)
-ss
java.lang.Exception
    at Main.go(Main.java:29)
    at Main.<init>(Main.java:21)
    at Main.main(Main.java:17)

      

0


source







All Articles