Is main method compulsory in Java?
The main() method is an entry point for all the programs in Java. Whenever we execute a program in Java, the JVM (Java virtual machine) searches for the main method to start its execution.
public static void main(String args[])
{
// block of code
}
Before JDK 7, it was possible to compile and execute the Java program without the main method. But since JDK 7, it is made compulsory to include the main method in order to execute and compile a program in Java.
Execution of Java program without main method
- Before JDK 7, It was possible to execute a Java program with the help of a static block.
- The static blocks are run at the time of class loading, prior to the main method, as it does not need any creation of an object or instance.
Note: The following program will be executed on both the JDK versions (i.e. prior to 7 and also since JDK 7), as the compilation of the Java program does not need a main method.
Filename: WithoutMainMethod.java
// Below program will be executed successfully on JDK versions before 7
class WithoutMainMethod
{
static
{
System.out .println ( "I am learning Java!" ) ;
}
}
JDK version prior to 7
As shown in the output, the program is compiled and executed successfully to produce the output.
Prior to Java 7, we needed to have one of the following to execute a Java program.
- -main() method
- static block
Output:
I am learning Java!
Exception in thread "main" java.lang.NoSuchMethodError: main
JDK version 7,8,9 ….
When run in JDK version 7 or after, the program will be compiled successfully without any error, but it will produce an error at runtime, as shown in the output below. Since JDK 7, the compiler first searches for the main method; if not found, it will produce an error at runtime: "Main method not found in class, please define main method".
To make a program executable, it needs to have a main method.
Output:
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application