Jones
Jones

Reputation: 1214

Why do Java main methods take "String[] args" parameters even when they are not used?

I've coded some in Ruby and C++, but in Java I don't understand what the String[] args parameter to the main method does.

Many simple Java ('hello world') examples are more or less like this:

public class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

From what I know about the syntax of other languages args would be used to pass command line arguments to the program. However, these simple examples don't make use of command line arguments.

So, why is the args parameter needed in situations like these when it isn't used?

Upvotes: 1

Views: 156

Answers (2)

siegi
siegi

Reputation: 5996

The signature of the method that is executed on JVM startup is specified in the Java language specification, §12.4.1:

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.

Thus you always have to add this parameter. Note that you can use String[] or String... as the type.

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Because this is not a dynamic language; the number and types of the arguments are part of the method signature, and all the following are different methods:

public static void main(String[] args)
public static void main(Object[] args)
public static void main()
public static void main(Collection<String> args)
public static void main(List<String> args)
public static void main(String[] args, String other)
public static void main(String other, String[] args)

Now, during runtime the proper method will be called that implements the most specific type parameters as determined during compilation. (note: this does not include parameter names).

This has as a side-effect that a main method must have a specific signature that will work for all cases. When you run without arguments, the args array will still be present, but have a zero length. If your program does not accept arguments, you're free to completely ignore the args parameter.

Upvotes: 1

Related Questions