Definition:
- A static block is a piece of code that is executed when the class is first loaded by the JVM.
- It is used to initialize static variables or perform tasks that need to be completed before the class can be used.
Purpose:
- Can be used to perform important initializations, such as establishing connections or calculating initial values.
- Useful for preparing the class before any instances are created or before static methods are called.
Execution:
- The static block is executed only once, as soon as the class is loaded, before any other code related to the class.
- It is executed even if no object of the class is created.
Code Example with Static Block:
StaticBlock.java
// Usa um bloco estático class StaticBlock { static double rootOf2; static double rootOf3; // Bloco estático para inicialização static { System.out.println("Inside static block."); rootOf2 = Math.sqrt(2.0); rootOf3 = Math.sqrt(3.0); } StaticBlock(String msg) { System.out.println(msg); } } class SDemo3 { public static void main(String args[]) { StaticBlock ob = new StaticBlock("Inside Constructor"); System.out.println("Square root of 2 is " + StaticBlock.rootOf2); System.out.println("Square root of 3 is " + StaticBlock.rootOf3); } }
Copy after login
e
- The message "Inside static block." shows that the static block was executed before the StaticBlock object was created.
- The values of rootOf2 and rootOf3 are calculated in the static block and are available before executing any method or object construction.
Advantage of Static Blocks:
They ensure that certain initializations are done safely and at the appropriate time, before the class is used.
Common Usage:
- Initiate complex static variables or perform initial configuration of resources that the class needs.
The above is the detailed content of Static Blocks. For more information, please follow other related articles on the PHP Chinese website!