One, ordinary code block
The {} that appears directly in a method is called a normal block of code, as shown in the example program:
public class codedemo01{
public static void Main (string[] args) {
Common code blocks
{
int x = 10;
System.out.println ("x=" + x);
}
int x = 100;
System.out.println ("x=" + x);
}
}
Ii. Building blocks of code
Code blocks {}, which are defined directly in the class without the static keyword, are called construction blocks of code, as shown in the example program:
public class codedemo02{
Public CodeDemo02 () {
System.out.println ("======== This is the tectonic method =========");
}
This is the construction code block, and when the new object is constructed, the code block first constructs the method to execute
{
System.out.println ("========= This is a tectonic block!=========");
}
public static void Main (string[] args) {
New CodeDemo02 ();
New CodeDemo02 ();
}
}
Third, static code block
A block of code declared with the static keyword is called a static code block, and the primary purpose of the static block is to initialize the static property, as shown in the example program:
public class CodeDemo03
{
static{
System.out.println ("This is a static block of code in the main class!");
}
public static void Main (string[] args) {
New Demo ();
New Demo ();
New Demo ();
}
}
Class Demo
{
static{
System.out.println ("This is a static block of code in the demo Class!");
}
{
System.out.println ("This is the building block in the Demo Class!");
}
Public Demo () {
System.out.println ("This is the construction Method!");
}
}
The static block takes precedence over the execution of the main method, and the static block takes precedence over the execution of the construction method and executes only once!
Iv. Synchronizing code blocks
Synchronous code blocks are mainly present in multiple threads.
PackageCn.sunzn.synchronize;
PublicClassSynchronizecode {
PublicStaticvoidMain (string[] args) {
NewThread () {
PublicvoidRun () {
while (True) {
System.out.print ("Sync"); SYSTEM.OUT.PRINTLN ("Code");
}
};
}.start ();
NewThread () {
Public void run () {
While (true) {
System.out.print ("Synchronize");
System.out.println ("Code");
}
};
}.start ();
}
}
4 types of code blocks in Java