In this post, we will see how to execute a Java program without main method.
We know that every Java program requires an entry point to start its execution. The entry point is usually a
main() method that drives the code. If
main() method is not found, an exception is thrown.
But before the
main() method is invoked, the Java Virtual Machine starts up by loading class into memory and the class is initialized by executing its static initializers and the initializers for static fields declared in the class.
As static initializers are executed before
main() method, it is possible to run a Java program without the
main() method by using static initializers as shown below:
public class Util
System.out.println("Java Program without main()");
Now as soon as Util class is loaded, the message will be printed. We have immediately called
System.exit(0) in the next line to prevent “main class was not found” exception.
Please note that this approach will not work in Java 7 and above. Even though the code will compile, it will throw below exception on execution:
The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String args).
In Java 7 and above, alternative is to write our own JVM launcher where we can define custom entry points to the application.
Also if the Java code is designed to be used as a library, the
main() method will not be present.
Thanks for reading.