Four types of Java code blocks

Source: Internet
Author: User

Four types of Java code blocks
I. Common Code Blocks

  The {} That appears directly in a method is called a common code block.The example program is as follows:

Public class CodeDemo01 {public static void main (String [] args) {// common code block {int x = 10; System. out. println ("x =" + x);} int x = 100; System. out. println ("x =" + x );}}

2. Construct a code block

   The code block defined directly in the class without the static keyword {} is called the Construction Code block.The example program is as follows:
Public class CodeDemo02 {public CodeDemo02 () {System. out. println ("========= this is the constructor ==========");} // This is the Construction Code block, and in the new object, construct a code block. Execute {System. out. println ("========= this is the construction block! ======== ");} Public static void main (String [] args) {new CodeDemo02 (); new CodeDemo02 ();}}

3. Static code block

  A code block declared using the static keyword is called a static code block. The main purpose of a static block is to initialize a static attribute.The example program is as follows:

Public class CodeDemo03 {static {System. out. println ("static block in the main class! ");} Public static void main (String [] args) {new Demo (); new Demo () ;}} class Demo {static {System. out. println ("static block in the class! ") ;}{ System. out. println (" constructor! ");} Public Demo () {System. out. println (" constructor! ");}}

Result chart:


Note that the static block takes precedence over the execution of the main method, and the static block takes precedence over the execution of the constructor method, and only runs once!

4. synchronous code block
The Synchronous Code block mainly appears in multiple threads.

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.