The execution sequence of static blocks, main methods, constructor blocks, and constructor methods.
If you encounter a problem with the execution sequence of static blocks, main methods, constructor blocks, and constructor methods, add this note.
The question is the order in which the following java code is printed after execution:
1 public class B 2 {3 public static B t1 = new B (); 4 public static B t2 = new B (); 5 {6 System. out. println ("build block"); 7} 8 static 9 {10 System. out. println ("static block"); 11} 12 public static void main (String [] args) 13 {14 B t = new B (); 15} 16}
Key points of this question:
Therefore, when JVM loads this class, because the priority levels of static blocks and static attributes are the same, the priority levels of the new two B objects are given to t1 and t2, therefore, the system prints the "build block" twice first, then executes the static block, prints the "static block", and finally executes the static main method. In the main method, a new B object is created, so print the "constructor block" again ".
The answer to this question is: Construct a block to construct a static block to construct a block.