Home  >  Article  >  Java  >  Can we execute Java program without main method?

Can we execute Java program without main method?

WBOY
WBOYforward
2023-09-01 21:45:061343browse

Can we execute Java program without main method?

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

A static block in Java is a set of statements that are executed only once when the Java ClassLoader loads a class into memory, also known as a static initialization block. Static initialization blocks go directly into 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 main method (until Java 1.6 version). Java 7 and newer versions do not allow this because the JVM checks for the existence of the main method before initializing the class.

Output

class without a main method.

The above is the detailed content of Can we execute Java program without main method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete