- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we change return type of main() method in java?
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 −
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)
- Related Articles
- Can we overload Java main method?
- Can the main method in Java return a value?
- Can we overload the main method in Java?
- Can we override the main method in java?
- Can we declare the main () method as final in Java?
- Can We declare main() method as Non-Static in java?
- Can we change the order of public static void main() to static public void main() in Java?
- Can we overload a method based on different return type but same argument type and number, in java?
- Can we create a program without a main method in Java?
- Can we declare a main method as private in Java?\n
- Can we change method signature in overriding in Java?
- Can we execute a java program without a main method?\n
- If I change the return type, will the method gets overloaded in java?
- Can we return this keyword from a method in java?
- Can we declare main() method as private or protected or with no access modifier in java?
