top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why main method is static in java?

+2 votes
415 views
Why main method is static in java?
posted Aug 9, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

public class JavaClass{
  protected JavaClass(int x){}
  public void main(String[] args){
  }
}

Should the JVM call new JavaClass(int)? What should it pass for x?

If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.

There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static.

answer Nov 7, 2017 by Manikandan J
...