This post will discuss how to execute a Java program without a 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 the main() method is not found, an exception is thrown.

But before the main() method is invoked, the Java Virtual Machine starts up by loading the 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 the main() method, it is possible to run a Java program without the main() method by using a static initializer, as shown below:

Download Code

 
Now, as soon as the Util class is loaded, the message will be printed. We have immediately called System.exit(0) in the next line to prevent the “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 the following exception on execution:


The program was compiled successfully, but the main class was not found.
Main class should contain method: public static void main(String[] args).

 
In Java 7 and above, an alternative is to write our own JVM launcher to 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.

That’s all about executing a Java Program without a main method.