Java static block consumer 1, java static

Source: Internet
Author: User

Java static block consumer 1, java static

The static block of the class is executed when the class is loaded. It is executed only once before the constructor.

The following example is helpful:

1 package untility; 2 3 public class A {4 // static block 5 static {6 A c; 7 System. out. println (200); 8 c = new A (); 9 I = 10; 10} 11 12 public static int I; 13 public int j; 14 15 public () {16 System. out. println (. i); 17 System. out. println (j); 18} 19 20 public static void main (String [] args) {21 A a = null; 22 System. out. println (100); 23 a = new A (); 24 // A B = new A (); 25} 26}

 

Running result:

20000100100

Resolution:

The program proceeds from the main method, executes the code loading class to 21 lines, then executes the static module, continues to execute the class to 6th lines, loads the class again, and runs it to the static module again, at this time, Row 3 has been executed once, so it will not be executed again (after writing the static Block 2 of the Java class, I found that the description here is problematic and Class A will not be loaded again here, only 7th rows are repeatedly executed), and then 7th rows are executed. Therefore, the first output is 200, and then the constructor of 8th sentences is executed (not to 9th sentences, so I and j are both 0), print out two 0, and then continue to execute the 9th sentence in the static module. At this time, I = 10, and the loading class is completed, then, execute the = null statement in 21 rows, print 22 rows, output 100, and finally execute the constructor in 23rd rows, and print 10 0 (because I is static ).

Related Article

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.