Can we execute a java program without a main() method?
Yes, you can compile and execute without main method by using a static block. However, after static block executes, you will get an error saying no main method found.
And latest info, you can't 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.
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
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.
Now - no
Prior to Java 7:
Yes, sequence is as follows:
- jvm loads class
- executes static blocks
- looks for main method and invokes it
So, if there's code in a static block, it will be executed. But there's no point in doing that.
How to test that:
public final class Test {
static {
System.out.println("FOO");
}
}
Then if you try to run the class (either form command line with java Test
or with an IDE), the result is:
FOO
java.lang.NoSuchMethodError: main