Execute a Java program without a main method
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:
|
1 2 3 4 5 6 7 8 |
class Main { static { System.out.println("Java Program without main()"); System.exit(0); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)