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

Can we execute Java program without main method?

WBOY
Release: 2023-09-01 21:45:06
forward
1405 people have browsed it

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);
   }
}
Copy after login

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.
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template