- 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 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)
- Related Articles
- Can we declare the main () method as final in Java?
- Can we declare a main method as private in Java?\n
- Can we declare an abstract method final or static in java?
- Can we declare a static variable within a method in java?
- Can we declare main() method as private or protected or with no access modifier in java?
- Can we make static reference to non-static fields in java?
- Can we overload Java main method?
- Can we declare constructor as final in java?
- Can we change the order of public static void main() to static public void main() in Java?
- Can we declare a constructor as private in Java?
- Can we declare an interface as final in java?
- Can we overload the main method in Java?
- Can we override the main method in java?
- Can we override the static method in Java?
- Can we create non static variables in an interface using java?
