Static and non-static code blocks in Java

Source: Internet
Author: User

Static and non-static code blocks in Java

Static code block:

Static {}

The execution priority is higher than that of non-static initialization blocks. It will be executed once when the object is loaded to the system and destroyed after the execution is complete. It can only initialize class variables, that is, static modified data members.

Non-static code block:

{}

If a static initialization block exists during execution, the static initialization block is executed first and then the non-static initialization block is executed. Each object is executed once and can initialize instance variables of the class. Non-static initialization blocks are run before the main code of the constructor is executed during the constructor execution.

Routine:

Public class Test1 {public static String staticField = "static variable"; public String field = "variable"; static {System. out. println (staticField); System. out. println ("static initial block");} {System. out. println (field); System. out. println ("initialization block");} public Test1 () {System. out. println ("constructor");} public static void main (String [] args) {new Test1 (); System. out. println (); new Test1 ();}}

Routine running result:

Static variables
Static initial block
Variable
Initialization Block
Constructor

Variable
Initialization Block
Constructor

  

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.