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?
- 3,315
- 7
- 21
- 31
-
http://stackoverflow.com/q/1672083/139010 – Matt Ball May 09 '13 at 00:50
4 Answers
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
- 166,747
- 40
- 210
- 420
- 29,583
- 5
- 70
- 94
-
-
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
-
-
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
If it is for a main(String[]) it is to fulfill the method signature & therefore vital.
- 166,747
- 40
- 210
- 420
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)
- 90,944
- 18
- 150
- 184
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.
- 713
- 1
- 5
- 13