22 May, 2014

How to run a Java Application without main method?

public static void main(String[] args) is usually considered the entry point of an application (which is true). But there is a case where we can tweak around and omit the need of main method completely. The answer lies in the keyword "static".
A static block is one per class block (not part of objects). Since this block is one per class, it will be called at the time of class load, not at the time of object creation. Usually this block is used to initialize static variables of the class.
Static blocks are loaded first in JVM (even prior to main method). We can even call other static methods from this block (exactly similar to main method).
consider the code below:
public class WithoutMain{
static{
System.out.println("Hello world");
}
}
When this class is loaded in JVM, the anonymous static block is loaded and executed before anything else and the SysOut statement is executed.
Being said this, the entry point remains still the same (main method) i.e. even if static block is present, the JVM will look for main method. if this method does not exist, following exception would be raised
Exception in thread "main" java.lang.NoSuchMethodError: main
We can even tweak around this. The exit(int) method of System class is used to exit the program. The int argument defines the state of program exit. A successful program will exit with a state '0'. Hence writing a statement System.exit(0); would immediately end the application (before JVM can try to find the main method). 

public class WithoutMain{
static{
System.out.println("Hello world");
System.exit(0);
}
}
PS:
Once I wrote this article, my friends started complaining that a program without main method could not be run. This was because they were trying to run the application from an IDE. When an IDE detects that the class doesn't contain main method, it is considered that there is no direct entry point (remember that this is a tweak) hence the UI of IDE doesn't displays "run as" options. To test above, try running the application by the naive method, through command prompt.