Is main method compulsory in Java?


To compile a program, you doesn’t really need a main method in your program. But, while execution JVM searches for the main method. In the Java the main method is the entry point Whenever you execute a program in Java JVM searches for the main method and starts executing from it.

The main method must be public, static, with return type void, and a String array as argument.

public static int main(String[] args){
}

You can write a program without defining a main it gets compiled without compilation errors. But when you execute it a run time error is generated saying “Main method not found”.

Example

In the following Java program, we have two methods of same name (overloading) addition and, without main method. You can compile this program without compilation errors.

public class Calculator {
   int addition(int a , int b){
      int result = a+b;
      return result;
   }
   int addition(int a , int b, int c){
      int result = a+b+c;
      return result;
   }
}

Run time error

But, when you try to execute this program following error will be generated.

D:\>javac Calculator.java

D:\>java Calculator
Error: Main method not found in class Calculator, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

To resolve this you need to define main method in this program and call the methods of the class.

public class Calculator {
   int addition(int a , int b){
      int result = a+b;
      return result;
   }
   int addition(int a , int b, int c){
      int result = a+b+c;
      return result;
   }
   public static void main(String args[]){
      Calculator obj = new Calculator();
      System.out.println(obj.addition(12, 13));
      System.out.println(obj.addition(12, 13, 15));
   }
}

Output

25
40

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements