Why does main method in Java always need arguments?

Basically, there are four answers:

  1. Because that's the way it was designed. Yea, I know that's a circular reason. But the point is that this is the way it is and it ain't going to change. So unless you are planning on designing your own language, the question is moot.

  2. Cleanness of design (aka the DRY principle). Don't specify two entry point signatures when one can do the job. And clearly, it can.

  3. Semantic simplicity. Suppose (hypothetically) that Java did support both void main(String[]) and void main() entry points. What would happen if a class defined both methods? Is that an error? If not, which one takes precedence when there is ambiguity? Is this confusing yet?

    By only recognizing void main(String[]), the JLS avoids that problem1.

  4. This is analogous to the standard C and C++ entrypoint signatures. (Admittedly, some C / C++ runtimes support other non-standard entrypoints as well ... but that's not exactly a good thing ... IMO.)

None of this means that it would have been unambiguously wrong to do it another way. And for example C# gives you alternative signatures, and deals with the ambiguity problem by requiring the developer to designate an entry point some other way.

FWIW, this wikipedia page describes the "main" method in a number of languages.


1 - Though then you have the "problem" that people who are new to Java might guess (incorrectly) that multiple entry points ought to work, try it, and get a surprise. But I don't think any design could cope with "programming by guesswork".


Because the java tool that runs the application looks for a main with a specific signature, so it knows it's calling the right one. Java has method overloading, so when looking up a method, you have to specify a fairly complete signature. Granted the java tool could do something more complex (look for the specific signature and, not having found it, look for any main and call it if it only finds one), but that's not what the Java designers decided to do (and subjectively, FWIW, I think that's for the best — keep it simple).

You can find the details in the Java Language Specification, Chapter 12: Execution. And note that as of when Java got variable argument lists, it became possible to declare main in two different ways:

public static void main(String[] args)
// or
public static void main(String... args)

Tags:

Java

Main