Can I write a Java program without main method ?
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.
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); } }
The Output could be as shown below in java 6.
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)
The program given below will run successfully, by adding an empty main() method in the program as shown below.
This executes successfully in java 7.
Reference Books:
//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: