Java static Block

Source: Internet
Author: User

1. Java organizes multiple static initialization actions into a special "static clause", which is a static block.
2. the initialization code in the static block will be executed together.

Public class staticbolck1 {// static block static {staticbolck1 A = new staticbolck1 (); I = 10;} public static int I; Public Int J; Public staticbolck1 () {system. out. println ("= 1111 ="); system. out. println (staticbolck1. I); system. out. println ("= 2222 ="); system. out. println (j); system. out. println ("= END =");} public static void main (string [] ARGs) {staticbolck1 A = new staticbolck1 ();}}
Output:
= 1111 =
0
= 2222 =
0
=== End ====
= 1111 =
10
= 2222 =
0
=== End =

Note:
The static module is first loaded and only loaded once during class loading, and the constructor can load the module multiple times.

The loading sequence is static module and constructor.
In the main method (program entry) main method, new A (); so static {} is loaded {}.

New A is added again in static, so its constructor is called public (){},

At this time, the printed content is I = 0 J = 0, both of which are initialized values.

After the static module is loaded, it loads its constructor.

In this case, the value of I in static is 10 and J remains unchanged. Therefore, I = 10 J = 0 is printed in the second call of the constructor.

In addition, there is a usage in Java called "non-static block", which has the same function and initialization sequence as "static block.

The only difference is that "non-static block" is not static and does not have the static keyword.

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.