4 types of code blocks in Java

Source: Internet
Author: User

/*

============================== learned something new ==============================================
differences between static code blocks, construction code blocks, and constructors
Static code block: Used to initialize a class, the class loads when it is loaded to execute, function: to initialize the class, only once.
constructs a code block: Used to initialize an object. This part is executed as long as the object is created, and takes precedence over the constructor.
constructor: When an object is initialized for the corresponding object, the corresponding constructor is selected to initialize the object.
Synchronous code block: The synchronization code block mainly appears in multi-threading.
Ordinary code block: {} that appears in a method or statement is called a normal code block. The normal code blocks and the general order of execution of statements are determined by the order in which they appear in the code-"first occurrence first".
when an object is created, the three are loaded in the execution order: static code block---> Construct code block---> Constructors
*/
Public class Test2 {

Public static void Main (string[] args) {
//TODO auto-generated method stub
{
System.out.println ("Normal code block 1");

}
new Test2 ();

{
System.out.println ("Normal code block 2");

}
System.out.println ();

new Test2 ();
}
Public Test2 ()
{

System.out.println ("======== This is the tectonic method =========");

}

{
System.out.println ("========= This is a tectonic block =========");
}

Static
{

System.out.println ("========= This is static block =========");

}

}

Execution Result:

========= This is a static block =========
Common code block 1
========= This is the construction block =========
======== This is the construction method =========
Common code block 2

========= This is the construction block =========
======== This is the construction method =========

4 types of code blocks in Java

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.