Is main() method compulsory in Java?

Here, we are going to learn about the main() method in Java: Is main() method compulsory in Java? Can we write a java program without main() method? By Preeti Jain Last updated : January 02, 2024

Is main() method compulsory in Java?

Yes, we can write a Java program without the main() method but there is a condition if and only if the Java JDK version till JDK 5. Till Java JDK 5 main() method was not compulsory to include in the Java program.

If we don't write our code in the main() method or don't include the main() method in our program then, in that case, we need to write our code under static block only, in that case, we can execute our code normally as we do.

Java example without main() method

// Java Program to demonstrate till Java JDK5 version 
// without main() method is possible.
class WithoutMainMethod {
    static {
        int i = 2, j = 4, sum;

        sum = i + j;

        System.out.println("The sum of i and j is :" + sum);
        System.out.println("This program is without main() valid till JDK 5 version");
    }
}

Output

The output of the above example is:

E:\Programs>javac WithoutMainMethod.java

E:\Programs>java WithoutMainMethod
The sum of i and j is : 6
This program is without main() valid till JDK 5 version

The main() Method in Java: Why It should be there?

In the case of the static block that static block executes before the main() method. Static block executes at the time of class loading.

In the case of the main() method, our program starts executing from the main() method, or in other words it is the starting point of the program execution. We can call the main() method directly without the creation of an object because it is static.

Till Java JDK 5 main() method was not mandated, But from Java JDK 6 main() is mandatory and if we don't include the main() method in our program then we will get RuntimeException "main method not found in the class".

Java example with main() method

// Program to demonstrate without main() method 
// from Java JDK 6 version
class WithoutMain{
	int i=2 , j=4 , sum=0;
	sum = i + j;
	System.out.println("The sum of i and j is :" + sum);
	System.out.println("This program without main() is not valid from JDK 6 version");
}

Output

The output of the above example is:

E:\Programs>javac WithoutMain.java

E:\Programs>java WithoutMain
Error: Main method not found in class WithoutMain, please define the main method as:
   public static void main(String[] args)

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.