
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Declare Main Method as Non-Static in Java
The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line.
You can write the main method in your program without the static modifier, the program gets compiled without compilation errors.
But, at the time of execution JVM does not consider this new method (without static) 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 in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static.
import java.util.Scanner; public class Sample{ public void main(String[] args){ System.out.println("This is a sample program"); } }
Output
On executing, this program generates the following error −
Error: Main method is not static in class Sample, please define the main method as − public static void main(String[] args)