The execution sequence of static blocks, main methods, constructor blocks, and constructor methods.

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.