-1

When I see Java programs, many leave the String args[] on even though the program doesn't use them. Why is this? Anything in particular?

MarJamRob
  • 3,395
  • 7
  • 22
  • 31

4 Answers4

10

String args[] is part of the method signature for main. If you don't have it you will get the exception below when you try and run the code.

Exception in thread "main" java.lang.NoSuchMethodError: main
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
FDinoff
  • 30,689
  • 5
  • 75
  • 96
  • http://pastebin.com/5KQYZ1VV This runs fine for me, though... – MarJamRob May 09 '13 at 00:50
  • I get the exception when I use the java compiler for mac (version javac 1.6.0_45). What compiler are you using? – FDinoff May 09 '13 at 00:52
  • javac 1.7.0_10 on OSX 10.7 – MarJamRob May 09 '13 at 00:54
  • I don't have that specific compiler on my computer. When I tried it with a javac version 1.7.0_11 on Fedora. I got a `Error: Main method not found in class tut21, please define the main method as: public static void main(String[] args)` So I do not know why you can run it. You shouldn't be able to. – FDinoff May 09 '13 at 00:58
  • @MarJamRob, either your compiler is broken or you're not running the class file you think you are. JLS7 explicitly states the parameter is required (see KevinB's answer). – paxdiablo May 09 '13 at 01:01
7

If it is for a main(String[]) it is to fulfill the method signature & therefore vital.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

Its required by the specification.

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)

public static void main(String... args)

Specification

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

The code within the main may not directly use it, but it is still required. 'String args[]' is where any command line arguments are passed. Even if you pass in 0 arguments, there needs to be a way for that to be verified. It is also the required signature for main by the requirements of the JVM.

minhaz1
  • 733
  • 1
  • 5
  • 13