[java] Can we execute a java program without a main() method?

According to my knowledge we cannot execute without a main method because when your running the java program. java Virtual machine look for the main method .if JVM could not find the main method it will show you run time error Exception in thread main could not find the main class.

But I searched for many blogs and some of them are saying, yes it can be done through static blogs if there is a static block in a java program,the class loader loads all static block before java gives call to main() method!.

Is it really possible and what will be the usability of these.

This question is related to java

The answer is


You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.


Since you tagged Java-ee as well - then YES it is possible.

and in core java as well it is possible using static blocks

and check this How can you run a Java program without main method?

Edit:
as already pointed out in other answers - it does not support from Java 7


Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.