Explain the four code blocks in java

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

I brief introduction

1. Common code block:

Method body of method in class

2. Construct code block:

The building block is called when the object is created, and is called every time it is created, which takes precedence over the class constructor.

3. Static code block:

Code snippets wrapped in static {} are executed only once. Static code blocks take precedence over building blocks.

4. Synchronization code block:

Using the code block wrapped by synchronized () {}, in a multithreaded environment, the read and write operations of shared data need to be mutually exclusive, otherwise it will lead to data inconsistency. Synchronization code blocks need to be written in methods.

II Similarities and differences between static code block and constructive code block

The same point: it is executed after the JVM loads the class and before the constructor is executed. Multiple variables 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 at the first new, and not later. Instead of static code blocks, they are executed every new time.

III Example

Common code block: the {} that appears in a method or statement is called a common code block. The execution order of ordinary code blocks and general statements is determined by the order in which they appear in the code. First appear, first execute.

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

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

public class Test1 {
    {
        System.out.println("First building block");
    }
    public Test1(int i) {
        System.out.println("The first" + i + "Call times" + "Construction method");
    }
    {
        System.out.println("Second building block");
    }
    public static void main(String[] args) {
        new Test1(0);
        new Test1(1);
        new Test1(2);
    }
}
/* 
 * Execution result first building block 
 *      Second building block 
 *      Call constructor for the 0 th time 
 *      First building block 
 *      Second building block 
 *      Calling the constructor for the first time 
 *      First building block 
 *      Second building block 
 *      Call the constructor for the second time 
 */

Static code block: a code block declared in java using the static keyword. The static block is used to initialize the class and initialize the attributes of the class. Each static code block is executed only once. Because the JVM executes static code blocks when loading classes, static code blocks execute before the main method.

If the class contains multiple static code blocks, the code defined first will be executed first, and the code defined later will be executed later.

be careful:

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

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

public class Test3 {
    public static String STATIC_FIELD = "Static properties";
    // Static block 
    static {
        System.out.println(STATIC_FIELD);
        System.out.println("Static code block 1");
    }
    public String field = "Non static attribute";
    // Non static block 
    {
        System.out.println(field);
        System.out.println("Non static code block 2");
    }
    public InitOderTest() {
        System.out.println("non-parameter constructor ");
    }
    public static void main(String[] args) {
        InitOderTest test = new InitOderTest();
    }
    // 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 attribute 
 *      Non static code block 2 
 *      Non static attribute 
 *      Non static code block 1 
 *      non-parameter constructor  
 */

The following code demonstrates the precedence between code blocks that create an object and call a method:

public class Person {
    static{
        System.out.println("1.I am a static block, which takes precedence over the construction block! And only execute once when creating the first object!");
    }
    {
        System.out.println("2.I am a construction block, which takes precedence over the execution of construction methods! Execute every time you create an object!");
    }
    public Person() {
        System.out.println("3.I am a constructor that executes every time an object is created");
    }
    public void function1(){
        System.out.println("I am an ordinary code block in a non static method, which is executed when the method is called!");
    }
    public static void function2(){
        System.out.println("I am an ordinary code block in a static method. When the method is called, it is executed later than the static block!");
    }
}

Test class:

public class HelloWrold {
    public static void main(String[] args) {
        new Person().function1();
        new Person().function1();
        System.out.println("=================");
        Person.function2();
        Person.function2();
    }
}

Operation results:

We can see that: the static block is always executed first, and it will only be executed once when the first instance of the class is created; The second execution is the construction block; The third execution is the construction method.

Keywords: Java Back-end

Added by olimits7 on Thu, 06 Jan 2022 05:14:13 +0200