The static block executes when classloader loads the class. A static block is invoked before main() method. Let us see an example −
Example
class Demo{ static int val_1; int val_2; static{ val_1 = 67; System.out.println("The static block has been called."); } } public class Main{ public static void main(String args[]){ System.out.println(Demo.val_1); } }
Output
The static block has been called. 67
A class named Demo contains a static integer value and a normal integer value. In a static block, a value is defined, and in the main class, an instance of the Demo class is created and the static integer is accessed from there.