Concept: A block of code refers to a piece of code enclosed in {}. Depending on the location and the keywords that are declared, the code block can be divided into ordinary code blocks, building blocks, static code blocks, and synchronous code blocks of 4. 1. Common code blocks:
Defined directly in a method or in a statement
Public class Test2 { publicstaticvoid main (string[] args) { // defines an ordinary code block int x =; // defining local Variables System.out.println ("Normal code block x=" +x); } int x = +; // Same as local variable name System.out.println ("Outside the code block x=" +x);} }
Operation Result:
Common code block x=30
Outside the code block x=100
2. Building Blocks:
Constructing a code block is a block of code that is written directly in the class.
Public classDemo {{//Defining building BlocksSystem.out.println ("1, building block. "); } PublicDemo () {//Defining construction MethodsSystem.out.println ("2, construction Method")); }} Public classTest2 { Public Static voidMain (string[] args) {NewDemo (); NewDemo (); }}
Execution Result:
1, building blocks.
2. Construction method
1, building blocks.
2. Construction method
From the output, it is found that the construction block is better than the construction method, and the building blocks are executed each time the object is instantiated.
Static code block:
A static code block is a block of code declared with the static keyword.
Public classDemo {{//Defining building BlocksSystem.out.println ("1, building block. "); } Static{System.out.println ("0, Static code block");//defining static code blocks } PublicDemo () {//Defining construction MethodsSystem.out.println ("2, construction Method")); }} Public classTest2 {Static{//defining static code blocks in the class where the Main method residesSYSTEM.OUT.PRINTLN ("Defining static code blocks in the class where the Main method resides"); } Public Static voidMain (string[] args) {NewDemo ();//instantiating an object NewDemo (); }}
Execution Result:
Defining static code blocks in the class where the Main method resides
0. Static code block
1, building blocks.
2. Construction method
1, building blocks.
2. Construction method
From the output, it is found that static code blocks are better than the main method, and static blocks of code defined in the class are better than the construction methods, and static blocks are executed only once, regardless of the number of objects produced.
4. Synchronizing code blocks:
Add the Synchronized keyword to the code block, which is mainly used on multi-threaded, this block of code is called the synchronous code block format as follows:
Synchronized (synchronization object) {
Code that needs to be synchronized;
}
Follow-up multithreading for more detailed exercises.
Object-Oriented---java code block