Static block (static block)

Source: Internet
Author: User

From: http://www.cnblogs.com/o-andy-o/archive/2011/12/28/2304959.html

The static block is executed only once when the class is loaded.

Class usestatic {

Static int A = 3;

Static int B;

Static void meth (int x ){

System. out. println ("x =" + x); system. out. println ("A =" + a); system. out. println ("B =" + B );

}

Static {

System. Out. println ("static block initialized .");

B = A * 4;

}

Public static void main (string ARGs []) {

Meth (42 );

}

}

 

Once the usestatic class is loaded, all static statements are run. First, a is set to 3, then the static block is executed (print a message), and finally, B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to X. The three println () Statements reference two static variables A and B, and the local variable X. Note: It is invalid to reference any instance variable in a static method. Below isProgramOutput:

Static block initialized.

X = 42

A = 3

B = 12

One step at a time to facilitate your review

 

The static block is executed only once when the class is loaded.

Class usestatic {

Static int A = 3;

Static int B;

Static void meth (int x ){

System. out. println ("x =" + x); system. out. println ("A =" + a); system. out. println ("B =" + B );

}

Static {

System. Out. println ("static block initialized .");

B = A * 4;

}

Public static void main (string ARGs []) {

Meth (42 );

}

}

 

Once the usestatic class is loaded, all static statements are run. First, a is set to 3, then the static block is executed (print a message), and finally, B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to X. The three println () Statements reference two static variables A and B, and the local variable X. Note: It is invalid to reference any instance variable in a static method. The output of the program is as follows:

Static block initialized.

X = 42

A = 3

B = 12

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.