- 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
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
- Related Articles
- Why the main () method in Java is always static?
- Can we overload Java main method?
- Can we overload the main method in Java?
- Why main() method must be static in java?
- Can we override the main method in java?
- What happens if NullPointerException is not handled in main method of java?
- Can the main method in Java return a value?
- What is overloading? What happens if we overload a main method in java?
- Can we change return type of main() method in java?
- Can we declare the main () method as final in Java?
- Can We declare main() method as Non-Static in java?
- Is main a keyword in Java?
- Why the main method has to be in a java class?
- How to execute a static block without main method in Java?
- Can we create a program without a main method in Java?
