Four types of Java code blocks
I. Common Code Blocks
The {} That appears directly in a method is called a common code block.The example program is as follows:
Public class CodeDemo01 {public static void main (String [] args) {// common code block {int x = 10; System. out. println ("x =" + x);} int x = 100; System. out. println ("x =" + x );}}
2. Construct a code block
The code block defined directly in the class without the static keyword {} is called the Construction Code block.The example program is as follows:
Public class CodeDemo02 {public CodeDemo02 () {System. out. println ("========= this is the constructor ==========");} // This is the Construction Code block, and in the new object, construct a code block. Execute {System. out. println ("========= this is the construction block! ======== ");} Public static void main (String [] args) {new CodeDemo02 (); new CodeDemo02 ();}}
3. Static code block
A code block declared using the static keyword is called a static code block. The main purpose of a static block is to initialize a static attribute.The example program is as follows:
Public class CodeDemo03 {static {System. out. println ("static block in the main class! ");} Public static void main (String [] args) {new Demo (); new Demo () ;}} class Demo {static {System. out. println ("static block in the class! ") ;}{ System. out. println (" constructor! ");} Public Demo () {System. out. println (" constructor! ");}}
Result chart:
Note that the static block takes precedence over the execution of the main method, and the static block takes precedence over the execution of the constructor method, and only runs once!
4. synchronous code block
The Synchronous Code block mainly appears in multiple threads.