Can we change return type of main() method in java?

Java 8Object Oriented ProgrammingProgramming

The public static void main() method is the entry point of the Java program. Whenever you execute a program in Java, the JVM searches for the main method and starts executing from it.

You can write the main method in your program with return type other than void, the program gets compiled without compilation errors. 

But, at the time of execution JVM does not consider this new method (with return type other than void) as the entry point of the program.

It searches for the main method which is public, static, with return type void, and a String array as an argument.

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

If such a method is not found, a run time error is generated.

Example

In the following Java program, we are trying to write the main method with the return type integer −

 Live Demo

import java.util.Scanner;
public class Sample{
   public static int main(String[] args){
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();
      System.out.println("This is a sample program");
      return num;
   }
}

Output

On executing, this program generates the following error −

Error: Main method must return a value of type void in class Sample, please
define the main method as:
public static void main(String[] args)
raja
Published on 03-Jul-2019 12:08:57
Advertisements