1. Local code block:
Format: Execute statement in method {Local code block}
Local code block, also known as normal code block. It is a block of code that acts in a method.
Function: Is the life cycle of the control variable.
In the program when we define a local variable x, and in the next code, no longer want to use it, then there is no need for X to continue to occupy space in memory. Therefore, there is a local code block.
2. Construct code block:
Format: In class {construct code block EXECUTE statement}
Function: initializes all objects.
Note the points:
1) Every time you create an object, he will execute it.
2) The construction code is faster than the constructor function execution.
3) The difference between constructing a block of code and a constructor is that constructing a block of code is a unified initialization of all objects, and the constructor initializes the corresponding object.
Because constructors can be multiple, which constructor is run, the same construction code block will be executed regardless of which object is created.
In other words, the initialization content of different object commonalities is defined in the Construction code block.
3. Static code block:
Format: Execute statement static{static code block in class}
Function: initializes the class.
When a class enters memory, static code is loaded first, such as static code blocks, variables modified with static, functions, and so on. Static blocks of code are used to initialize classes. The constructor is the initialization of the object,
A static code block can initialize a class as if static variable num modifies his value in a static block of code. Static blocks of code can also be useful in situations where you do not need to instantiate a class.
Static code blocks in Java (static{...} ), local code block (method {...} ), construct the code block (class {...} Difference