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

18

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 tagged with java

~ Asked on 2013-03-02 10:35:35

The Best Answer is


31

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

~ Answered on 2013-03-02 10:39:45


5

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.

~ Answered on 2013-03-02 11:17:30


Most Viewed Questions: