Why does Java main() method accept an array of String args?

前端 未结 8 1333
情深已故
情深已故 2021-01-14 06:20

Since its possibly one of the most widely used methods of the Java language, why does it have to accept an array of Strings and doesn\'t work without it? For example, I coul

相关标签:
8条回答
  • 2021-01-14 06:56

    even a gui driven java app will start with some main method. The "higher purpose" has never been to accept command line arguments.

    The purpose is just to accept arguments. Period. Whenever you start any program not just Java you will always need some syntax to pass arguments

    0 讨论(0)
  • 2021-01-14 07:05

    Programs always take commandline arguments. It's up to the programmer to decide if they are used for anything.

    So implementing a main without a string-array would lead to more complex startup-logic and potentially confusing and errorneous behavior, for the more than debatable gain of not writing a single parameter declaration less (in your whole program!)

    And given the overall verbosity of Java & the support for common templates for boilerplate code in IDEs like Eclipse, I fail to see where that's really an issue.

    0 讨论(0)
  • 2021-01-14 07:05

    Lots of GUI programs provide facilities to accept command-line switches to control their behaviour at start up.

    0 讨论(0)
  • 2021-01-14 07:08

    there are also many java programs that receive args through command line. Think of javac, ant, maven, etc

    0 讨论(0)
  • 2021-01-14 07:09

    "Is there a higher purpose to this (..)"

    Yes: legacy.

    0 讨论(0)
  • I agree that it could be more flexible. In C# for instance, all of these are acceptable entry points:

    static void Main()
    static void Main(string[] args)
    static int Main()
    static int Main(string[] args)
    

    The versions returning int use the return value as the exit code for the process. If you don't care about receiving any arguments, you can use one of the versions which doesn't take any. Any arguments given when the program is launched are ignored.

    So yes, it could be more flexible - but it's never struck me as a significant problem in Java.

    0 讨论(0)
提交回复
热议问题