Can the main method in Java return a value?


The public static void main(String args[]) is the entry point of a Java program Whenever you execute a program the JVM searches for the main method and starts executing the contents of it. If such method is not found the program gets executed successfully, but when you execute the program it generates an error.

As the matter of fact you should declare the main method with public static as modifiers, void return type and String arguments if you change anything, JVM doesn’t considers as the entry point method and prompts an error at run time.

Therefore, you cannot change the return type of main method from void, at the same time you cannot return any value from a method with void type.

Example

public class Sample{
   public static void main(String args[]){
      System.out.println("Contents of the main method");
      return 20;
   }
}

Output

Sample.java:4: error: incompatible types: unexpected return value
   return 20;
          ^
1 error

Therefore, you cannot return any value from main.

Updated on: 06-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements