A static block in a program is a block which is associated with a static keyword. The static block executes when the classloader loads the class. A static block is invoked before the main() method in java.
Syntax:
.........
static {
.......statements
}
.......
Let us go through a static block example.
Static block in Java with Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class StaticTest { //static integer is declared static int num; //static block static { num = 100; //assigned the value System.out.println("This is Static block!"); } } //Main driver public class Main { public static void main(String args[]) { //printing the num value, but will be printed atlast System.out.println(StaticTest.num); } } |
Output:
This is Static block!
100
As you can see, the static block is executed first, and then the Main function in the above program.