Can We Run Java Program Without Main Method?

Prior to Java 7, yes, we could run Java program without main() method. But, from JDK7 main method is mandatory. The compiler will verify first, whether main() is present or not. If your Java program doesn't contain the main method, then you will get an error main method not found in the class.

Prior to Java 7: Yes, sequence was as follows:
- jvm loads class
- executes static blocks
- looks for main method and invokes it

Before Java 7 we could write full code under static block and it used to run normally. The static block is first executed as soon as the class is loaded before the main() method is invoked. Then main() is also declared as static; therefore, Java doesn't need an object to call the main() method.

Let's take an example

// This program successfully runs prior to JDK 7 
public class Test  
{ 
    // static block 
    static
    { 
        System.out.println("Hello User"); 
    } 
}

If you execute above piece of code then compiler presumes Test is that class which main() is defined in. Therefore, JVM loads the class and static block gets executed. So in above example, JVM runs static block first and then comes to know that there is no main() method in the class. Therefore, it throws "exception", as exception comes while execution. If we don't want an exception to be thrown, we can terminate the program by System.exit(0);

But from JDK7 main method is mandatory. Compiler will verify first, whether main() is present or not. If your program doesn't have a main method, you will get an error main method not found in the class. This error is generated during byte code verification because in byte code, main is not there.

Hope you have enjoyed reading this post. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.