Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Can a Java application run without a main method?


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
Advertisement
XyzWs Java FAQ: Can a Java application run without a main method?

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" );
    System.exit(0);
  }
} 

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.

 


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

Support  | Feedback  | Help