Static code block
Format:
Static
{
Execution statements in a static code block
}
Characteristics:
Executes as the class loads, executes only once, initializes the class, and takes precedence over the main function execution
Consider the following Java statement
Class staticcode{static {System.out.println ("a"); }}public class Demo {static {System.out.println ("B"); } public static void Main (string[] args) {new Staticcode (); New Staticcode (); System.out.println ("End"); } static {System.out.println ("C"); } }
The output is:
B
C
A <== Although there are two statements that call Staticcode, but because they contain only static blocks of code, static blocks only perform
Once, so only one A is output
End
Classes are loaded only when the content in the class is involved, and static blocks of code execute
Staticcode m = null; The <== class is not loaded
s = new Staticcode (); The <== class was loaded because the constructor Staticcode () in the class was used, so the static code block
will be executed
So judging if a class has not been loaded, you can use static code blocks to verify
Class staticcode{ staticcode () { system.out.println ("C"); } static { system.out.println ("a"); I } { system.out.println ("B"); II } staticcode (int x) { system.out.println ("hah"); iii } public static void test () { system.out.println ("succeed"); }}public class Demo { public static void Main (String[] args) { new Staticcode (5); } }
I-----A static block of code to initialize the class
II-----Constructing a code block to initialize the object
III-----constructor to initialize the corresponding object
Output Result:
A
B
Hah
Note: Static code blocks can only access static variables
Constructs a block of code that can be accessed to
"Java" Static code block