Wednesday, 29 April 2015

Why main method is static in Java

When we start learning java and make our first "Hello World" program, there are two things which stand out.

Here we'll talk about the main method. Coming to main method signature it is easy to see that main method is -

  • Public - Access modifier is public so that main method is visible to every other class, same package or other. If it is not public JVM classes will not be able to access it.
  • Void - As it does not return any value.
  • String[] args - arguments to this method. The main method takes an array of Strings as parameter, that array is called 'args'.

But why static is a question that needs some explanation.

Please read details about Why file name and class name should be same in Java. It is recommended before reading about why main method is static.

Now, when we know that at least at run time class name should be same, as that's how JVM knows which class to load and where is the entry point (main method). But how will JVM access that main method with out creating an instance of the class, answer is having main method as static.

If it is not declared as static then instance of the main class has to be created which may cause ambiguity,
consider the example -

public class A {
 private int i;
 A(int i){
  this.i = i;
 public static void main(String args[]){

Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main is static.

Points to note -

  • main method must be declared public, static and void if any of these are missing; java program will compile but at run time error will be thrown.
  • At run time interpreter is given the class file which has main method, thus main method is entry point for any java program.
  • Declaring main method as static ensures that JVM can invoke the entry point (main method) with out creating any instance of the class.
  • With varargs in Java 5 onward it is possible to write the main method as public static void main(String ... args).

That's all for this topic Why main method is static in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. static in Java
  2. static method overloading or overriding in Java
  3. static import in Java
  4. interface static methods in Java 8
  5. static reference to the non-static method or field error
  6. static block in Java

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment