1 Code block classification: code block in Java refers to the use of {} A piece of code, depending on the location of the different can be divided into four kinds:
Common code blocks
Construction Fast
Static code block
Synchronizing code blocks
Today, the main learning of the first three blocks of code, synchronization code block in the learning to the multi-threaded part of the time to add learning.
2 Normal code block: the code block directly defined in the method, as follows:
public class Codespace {public static void main (String args[]) {{int x = 30; SYSTEM.OUT.PRINTLN ("Common code block x=" +x);} System.out.println ("Outside the ordinary code block x=" +x); int x=10; System.out.println ("Outside the ordinary code block x=" +x);}}
3 Construct fast: Define code directly in the class
Class Codedemo{{system.out.println ("fast Construction");} Public Codedemo () {System.out.println ("construction Method");}}; public class Codespace {public static void main (String args[]) {new Codedemo (); new Codedemo (); new Codedemo ();}}
The result of the operation shows that the construction is executed first with the construction method, and the contents of the construction block are executed every instantiation of an object.
4 Static code block: a block of code declared directly with the static keyword
Class Codedemo{public Codedemo () {System.out.println ("construction Method");} {System.out.println ("construct Fast");} Static{system.out.println ("Class Codedemo Static code block");}}; public class Codespace {static{system.out.println ("class Codespace Static code block");} public static void Main (String args[]) {new Codedemo (); new Codedemo (); new Codedemo ();}}
Execution result analysis: Static code blocks are executed before the main method, static blocks defined in the normal class are executed when the class is instantiated, executed before the constructor, and static code is typically used to initialize static properties, regardless of how many instanced objects produce static blocks of code that are executed only once.
Java Learning Note Four (code block)