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.
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.
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!