2018-05-02
code block
What is a block of code?
In a class or method, use "{}" to encapsulate multiple lines of code together to form a separate code area, which constitutes a block of code.
A variable in a block of code is a local variable and is only valid within and before and after {} in its own region.
Classification of code blocks
Depending on the location defined by the code block, it is divided into three different
1, Local code block: in the method with a pair of "{}" in the data, is the local code block,
In general, we will not use the local code block directly, but we will combine if,while,for,try and other key words to represent a piece of code area.
2. Initialize code block (construct code block): code that is directly defined in the class, enclosed in "{}".
The constructor is used every time the object is created, and the initialization code block is executed before the constructor is called.
As you can see by anti-compilation, the initialization code block is also used as the constructor's original statement.
We generally do not use the initialization code block, even if you want to do the initialization operation, it is generally done in the constructor. If the code for the initialization operation is more, then the structure of the constructor is quite chaotic,
At this point, you can specifically define a method to do the initialization (initialization of the object) and then call it in the constructor.
3. initialization code block with static decoration:(in the class, in the position of the member, with "{}" in the enclosed code, but he used the static decoration,. )
Executes a static block of code before the main method executes, and executes only once
The Main method is the entry for the program, why does the static code block take precedence over the main method execution?
Because static members are loaded with bytecode loading, they are also loaded into the JVM. At this point the main method has not been executed because the method requires a JVM call.
That is, the bytecode is loaded into the JVM before the JVM calls the main method.
Generally we use it for initialization (initialization of classes), loading resources, loading configuration files, and so on.
Second, Java Object-oriented (10) _ code block