How to execute a java program without having a main () method: 

In Java, Up to Java 6 it was possible to do this using the Static Initialization Block. For solve the problem to a execute java program without having main method.

For example we have writing the following code using static block:



public class CheckWithoutMain{ 


  System.out.println("static block is Executed"); 




Output: (In JDK 6)

The System.exit (0); is used to the program exit before the JVM is looking for the main method, otherwise error will be thrown:

Exception in thread “main” java.lang.NoSuchMethodError:main


In Java 7 & above, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contains method: public static void main (String [] args).

Output: (In JDK 8)


So, we have only execute a java program without having main method up to valid Java versions 6.

  Modified On Nov-19-2017 09:51:15 AM

Leave Comment