Static block of Java class

Source: Internet
Author: User

A static block of a class executes at class load time, executes earlier than the constructor, and executes only once.

The following example can help to understand:

1  Packageuntility;2 3  Public classA {4     //static Block5     Static {6 A C;7SYSTEM.OUT.PRINTLN (200);8c =NewA ();9i = 10;Ten     } One  A      Public Static inti; -      Public intJ; -  the      PublicA () { - System.out.println (A.I); - System.out.println (j); -     } +  -      Public Static voidMain (string[] args) { +A A =NULL; ASYSTEM.OUT.PRINTLN (100); atA =NewA (); -         //a B = new A (); -     } -}

Operation Result:

20000100100

Analytical:

The program goes in from the main method, executes to 21 lines of code to load the class, then executes the static module, proceeds to line 6th, loads the class again, runs to the static module again, and the 6th line has been executed once, so it is no longer executed (After writing the Java class static block two found here the description is problematic, here will not be repeated loading Class A, will only repeat the 7th row), and then execute line 7th, so the first is printed out is 200, and then execute the 8th sentence of the constructor (not executed to the 9th sentence, so I and J are 0), Print out 2 0, then proceed to the 9th sentence in the static module, at this time i=10, to this load class complete, and then continue to execute 21 lines of the =null statement, in the execution of 22 lines of print, output 100, and finally execute the 23rd row of the constructor, printed out 10 0 (because I is static).

Static block of Java class

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.