Can a Java application run without a main method?

Yes, you can but do not count on it when you develop your application. In Java, a static initializer gets executed as soon as the class is loaded, even before the main method is called. Here is an example,

public class WithoutMain {
static {
System.out.println( "Hello World" );

The JVM finds and loads the class into memory when you run this code, the static initializer is executed during the loading and initialization of the class. System.exit(0) is called at the end of the static block to terminates the program. If not, then the JVM would have next used reflection on that class to find the main() method. If it does not find the main method, it throws an exception.

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |