articles

Home / DeveloperSection / Articles / How to execute a java program without having a main () method

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

Anupam Mishra6546 04-Dec-2015

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{ 
  static{    System.out.println("static block is Executed"); 
  System.exit(0); 
  } 

 

Output: (In JDK 6)



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


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


would contains method: public static void main (String [] args).


Output: (In JDK 8)


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

 

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


Updated 07-Sep-2019

Leave Comment

Comments

Liked By