What is a block of code
In Java, code that is enclosed in {} is called a block of code.
Code block classification
- Local code block: Code that is in the local variable position and enclosed in {} to limit the life cycle of the local variable.
- Building blocks of code: The position of the member variable in the class and the code enclosed in {}, and the construction method at the same level, are called once each time the constructor method is called, so it is called constructing the code block.
- Static code block: The position of the member variable in the class and the code enclosed in {}, but you need to add a static keyword before {}
What's the difference?
- Local code blocks are used in local locations to define the life cycle.
- The purpose of constructing a code block is to put together the same code in multiple construction methods, call once before instantiating the object, and multiple objects appear multiple times.
- Static code blocks occur when classes are initialized, and multiple objects share one.
- code block cannot be explicitly called
Sample code
/*** Created by Lili on 15/10/17.*/classcodearea{//Static code block Static { inty = 100; System.out.println (y); } //Building Code Blocks { intx = 10; SYSTEM.OUT.PRINTLN (x); } PublicCodearea () {System.out.println ("------construct function 1-------"); } //constructing a code block does not have to appear before the construction method and can be anywhere at the same level, but is called before the method is constructed. { intx = 20; SYSTEM.OUT.PRINTLN (x); } PublicCodearea (intm) {System.out.println ("------Construct function 2-------"); } { intx = 30; SYSTEM.OUT.PRINTLN (x); } //The static construction method, regardless of how many times it occurs, is called before the code block and construction method are constructed. Static { inty = 200; System.out.println (y); } { intx = 40; SYSTEM.OUT.PRINTLN (x); }} Public classCodeareatest { Public Static voidMain (String args[]) {{intx = 1; SYSTEM.OUT.PRINTLN (x); } System.out.println ("--------Split 1----------"); Codearea codeArea0=NewCodearea (); Codearea codeArea1=NewCodearea (1); }}
Run results
1--------split 1----------10020010203040------construct function 1-------10203040------construct function 2------- 0
Code blocks in Java basic Java