code block
Local code block
a local code block is defined in a method or statement
Features:
A region of code delimited with "{}", at which point you only need to focus on the different scopes
methods and classes delimit boundaries in a code block way .
class demo{
Public static void Main (string[] args) {
{
int x = 1;
System.out.println ("Normal code block" + x);
}
int x =;
System.out.println ("Outside the code block" + x);
}
}
Results:
Common code block 1
outside the code block
Building Code Blocks
Constructing a code block is a block of code that defines the position of a member in a class
Features:
takes precedence over construction method execution, and constructs code blocks to perform initialization actions that are required for all objects
Each object that is created executes a block of construction code at a time .
Public class Person {
private String name;
private int age;
//Construct code block
{
System.out.println ("Construction code block executed");
}
Person () {
System.out.println ("person with parameterless constructor execution");
}
Person (int age) {
this.age = age;
System.out.println ("The constructor of the person (age) argument executes");
}
}
class persondemo{
Public static void Main (string[] args) {
Person p = new Person ();
Person p1 = new Person (at all);
}
}
Static code block
A static code block is a block of code that is defined at the member location , using the static adornment.
Features:
it takes precedence over the execution of the Main method, which takes precedence over the construction of code block execution, when used in any form for the first time to the class.
The static code block executes only once, regardless of how many objects are created .
can be used to assign a value to a static variable for initialization of a class.
Public class Person {
private String name;
private int age;
//Static code block
static{
System.out.println ("Static code block executed");
}
}
Java-code block