Execute Java Program Without a Main Method



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.
Updated on: 2023-10-07T02:45:53+05:30

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements