Can we execute a java program without a main method?

JavaObject Oriented ProgrammingProgramming

Yes, we can execute a java program without a main method by using a static block. 

Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block. Static initialization block is going directly into the stack memory.

Example

class StaticInitializationBlock{
   static{
      System.out.println("class without a main method");
      System.exit(0);
   }
}

In the above example, we can execute a java program without a main method (works until Java 1.6 version). Java 7 and newer versions don’t allow this because JVM checks the presence of the main method before initializing the class.

Output

class without a main method.
raja
Published on 24-May-2019 14:44:46
Advertisements