Open In App

Is main method compulsory in Java?

The answer to this question depends on the version of java you are using. Prior to JDK 7, the main method was not mandatory in a java program.

 



However, from JDK7 main method is mandatory. The compiler will verify first, whether main() is present or not. If your program doesn’t contain the main method, then you will get an error “main method not found in the class”. It will give an error (byte code verification error because in it’s byte code, main is not there) not an exception because the program has not run yet.

Note:- However, both the programs will get compile because for compilation we don’t need main() method.




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

Below is the screenshot of the output to help you to visualize the same thing, practically. I have run this program on Notepad so that you can able to understand why that exception has changed into error in the latest version.



  • If run prior to JDK 7

    Output in JAVA 6 version.

  • If run on JDK 7,8 and so on…

    Output in JAVA 7

  • Article Tags :