Four types of code blocks in Java

Code blocks enclosed in {} are called code blocks in java. Code blocks can be divided into the following four types:

1. Introduction

1. Ordinary code block:

Method body of a method in a class

2. Construct the code block :

Constructor blocks are called when an object is created, and every time an object is created , taking precedence over class constructors.

3. Static code block:

Code snippets wrapped with static{} will only be executed once. Static code blocks are executed in preference to building blocks.

4. Synchronized code block:

Code blocks wrapped with synchronized(){}, in a multi-threaded environment, read and write operations on shared data need to be mutually exclusive, otherwise it will lead to data inconsistency. Synchronized code blocks need to be written in methods.

2. The similarities and differences between static code blocks and constructive code blocks

The same point: it is executed after the JVM loads the class and before the constructor is executed. Multiple classes can be defined in the class. Generally, some static variables are assigned in the code block.

Difference: Static code blocks are executed before non-static code blocks. Static code blocks are executed only once the first time new, and not after that. Instead of static code blocks are executed every time they are new.

3. Example

        Ordinary code block : {} appearing in a method or statement is called an ordinary code block. The order of execution of ordinary code blocks and ordinary statements is determined by the order in which they appear in the code, first-occurring-first-execution.


public class Test {
    public static void main(String[] args) {
        int x;
        {
             x = 3;
            System.out.println("Variable x=" + x in normal code block);
        }
         x = 1;
        System.out.println("Variable x=" + x in the main method);
        {
            int y = 7;
            System.out.println("Variable y=" + y in normal code block);
        }
    }
}
/*
 * The variable x=3 in the normal code block of the running result
 * The variable x=1 in the main method
 * Variable y=7 in normal code block
 */

        Construction code block : A code block defined directly in a class without the static keyword is called a {} construction code block. The constructor block is called when an object is created, every time an object is created, and the execution order of the constructor block takes precedence over the class constructor. If there are multiple building blocks, the order of execution is determined by the order in which they appear in the code, first appearing first.

public class Test {
    {
        System.out.println("First Building Block");
    }
    public Test1(int i) {
        System.out.println("th" + i + "call" + "constructor");
    }
    {
        System.out.println("Second Building Block");
    }
    public static void main(String[] args) {
        new Test1(0);
        new Test1(1);
        new Test1(2);
    }

}
/*
 * The first building block of the execution result
 * Second building block
 * 0th call to constructor
 * first building block
 * Second building block
 * 1st call to constructor
 * first building block
 * Second building block
 * 2nd call to constructor
 */

        Static code block : A block of code declared using the static keyword in java. A static block is used to initialize a class, to initialize the properties of the class. Each static code block will only be executed once. Since the JVM executes the static code block when the class is loaded, the static code block is executed before the main method.

If the class contains multiple static code blocks, it will be executed according to " the code defined first is executed first, the code defined later is executed ".

Notice:

1. Static code blocks cannot exist in any method body .

2. Static code blocks cannot directly access instance variables and instance methods, they need to be accessed through the instance object of the class.

3. Static variables cannot be defined in a static block. You can define static variables inside a class and then initialize operations in a static block.

public class Test {
    public static String STATIC_FIELD = "Static property";
    // static block
    static {
        System.out.println(STATIC_FIELD);
        System.out.println("Static block 1");
    }
    public String field = "Non-static property";
    // non-static block
    {
        System.out.println(field);
        System.out.println("Non-static code block 2");
    }
    public Test() {
        System.out.println("No parameter constructor");
    }
    public static void main(String[] args) {
        Test test = new Test();
    }
    // non-static block
    {
        System.out.println(field);
        System.out.println("Non-static code block 1");
    }
    // static block
    static {
        System.out.println(STATIC_FIELD);
        System.out.println("Static code block 2");
    }
}
/*
 * Run result static properties
 * static code block 1
 * static properties
 * static code block 2
 * non-static properties
 * Non-static code block 2
 * non-static properties
 * non-static code block 1
 * no-argument constructor
 */

Demonstrate the relationship between the various code blocks

public class HelloWorld {
    public static void main(String[] args) {
        new Person().function1();
        new Person().function1();
        System.out.println("=================");
        Person.function2();
        Person.function2();
    }
}
class Person{
    static{
        System.out.println("1. I am a static block, which takes precedence over the construction block! And only executes once when the first object is created!");
    }
    {
        System.out.println("2. I am a construction block, which is executed in preference to the construction method! Execute once every time an object is created!");
    }
    public Person() {
        System.out.println("3. I am a constructor, and execute it every time an object is created");
    }
    public void function1(){
        System.out.println("I am a normal code block in a non-static method, executed when the method is called!");
    }
    public static void function2(){
        System.out.println("I am a normal code block in a static method, which is executed when the method is called, after the execution of the static block!");
    }
}

It can be seen that: the static block is always executed first, and will only be executed once when the first instance of the class is created, the second executes the construction block, and the third executes the constructor


Finally, summarize the execution order of code blocks and variables:

1. Static (class variables, static code blocks) belong to the class itself and does not depend on the instance of the class

2. When creating a class instance object, the non-static code block is executed earlier than the constructor

3. The status of non-static (instance variables, non-static code blocks) is the same, they are executed in order, but they will still be executed before the constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325937296&siteId=291194637