In Java, starting point of any program is Main method and it can be placed in any class that’s part of a program.
But What if we want to run a program without a Main method. Can we do it ?
Answer is Yes. We can execute a program with help of "Static block" aka "static initialization block".
What is static block?
Static block is group of statements that gets executed once when Class Loader loads class.
Example :
class StaticExample {
static {
System.out.println("Hello World from static");
System.exit(0);
}
}
Output :
Hello World from static
Note: Above code will work till 1.6 version only. In new versions, JVM Checks for Main method before initialization.
Though it won't work for new versions, however it helps us in understanding how JVM class loaders works.
Top comments (0)