Why main() method must be static in java?


Static − If you declare a method, subclass, block, or a variable static it is loaded along with the class.

In Java whenever we need to call an (instance) method we should instantiate the class (containing it) and call it. If we need to call a method without instantiation it should be static. Moreover, static methods are loaded into the memory along with the class.

In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static.

When the main method is non-static

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.

 Live Demo

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)

Updated on: 29-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements