Powered by Blogger.

Can I write a Java program without main method ?

>> Thursday, August 13, 2015

Yes, We can write a java program without main method by using static block, only in java version 6. But not possible in later versions like java 7 or 8.
Before going to discuss "How to write a java program without main method", let's get an idea about the programs, which are running without main method.
Java Program without main method_JavabynataraJ
In Java, there are actually different types of execution model available, for example Applets, Servlets, MIDlets. Applets will run on browser and doesn't have main method, instead they have life-cycle methods like init(),start() and stop(), which controls their execution. Since Applet is a java program, we can run this without main method. Similarly, Servlet runs in a Servlet container, comes as bundled in web server like Tomcat, or Jetty. It has methods like init(),service(),destroy(), and this works on callback mechanism. Since Servlet is also a java program, we can say that it runs without main method. The Last one MIDlet, which runs on mobile devices, e.g. Nokia,Samsung and others. MIDlet has life-cycle methods like startApp(), pauseApp() and destroyApp(), to start, pause and shut-down mobile applications.Since MIDlets are also Java program, you can say they run without main method.

As we know, we can run a  java program without main method by writing code in static initializer block, which is true in java 6. Static initializer block is a set of statements, which will be executed by the JVM before execution of main method.
//author: javabynataraj.blogspot.com
public class WithoutMain {
  static {
  System.out.println("Hi Guys, Java progarm without main method");
  System.exit(0);
  }
}
Before compiling with different java version , change the classpath of the java to 6 or 7.
The Output could be as shown below in java 6.
Java Program without main method_Output
But the same program if you run in java 7 this will gives you a run time Error by saying as:

Error: Main method not found in class WithoutMain, please define the main method as:
   public static void main(String[] args)

Java Program without main method_Output2

The program given below will run successfully, by adding an empty main() method in the program as shown below.
//author: javabynataraj.blogspot.com
public class WithoutMain {
  static {
  System.out.println("Hi Guys, Java progarm without main method");
  System.exit(0);
  }
  public static void main(String[] args) {
  //empty
 }
}

This executes successfully in java 7.

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.