Execute a Java Program without main method

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:

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.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz