Create a Java Application without main method




Can we create and run a Java Application without main method?


The answer is Yes!

But how?

It can be done by having only a static block of the class. Let's check it out.


Let's create a WithoutMainMethod.java file and add following code in it:
class WithoutMainMethod {
    static {
        System.out.println("This Java program is running without main method");
        System.exit(0);
    }
}

Now, run the code using commands:
javac WithoutMainMethod.java
java WithoutMainMethod

We will get the output:
This Java program is running without main method

How is this possible?

The reason this worked is because the static block gets executed as soon as the class is loaded, even before the main method is called. During runtime JVM will search for the main method after exiting from this block. If it doesn't find the main method, it throws and exception.

To avoid the exception we used System.exit(0); at end of static block. This will terminate the program at the end of the static block and no exception will be thrown



Note:

The above method was valid for Upto and including Java 6.
However, this does not work anymore from Java 7, even though it compiles, the following error will appear when you try to execute it:

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



Previous Post Next Post