I'm a beginner in java.When executing a simple program I noticed that in main method
public static void main(String args[])
args[]
can be given any name and it executes successfully. Why is that?
I'm a beginner in java.When executing a simple program I noticed that in main method
public static void main(String args[])
args[]
can be given any name and it executes successfully. Why is that?
When you call a method, you don't care about what the names of its parameters are, do you?
Say I have this method:
public static void doStuff(int number) {}
And I can call it like this:
doStuff(10);
Do I need to use the parameter name number
anywhere in the calling code? No.
Even if you call the method by reflection, (which I think is what actually happens when you run a java program) you don't need the parameter names.
Method m = clazz.getMethod("main", String[].class);
m.invoke(null, null);
To put it bluntly: because the docs say so. 1
The main
must be public
, static
, void
and accept an array of String
s as it's parameter. The rest is up to the programmer... but there is not that much left other than the argument's name.
I can't speak for the many minds behind Java, but enforcing an argument's name is just not that important; the JVM doesn't care about a typo in args
when it wants to invoke the main
. What's important is the signature, which is defined by return type, name, and the type(s) of the argument(s) passed in.
The main method mus have a specific signature. The signature specifies method name and parameter types, but does not specify parameter names.
in other words, is must be public, static and void, be called main, and take an array of String as a parameter. It does not require a specific name for that parameter.
args
is just a variable name of the type String[]
. It is like any other variable name that you have inside your program.
as stated the variable name is only internal, the compiler does only care about the type (String array). for example if you call the method with reflection you can just pass a array of arguments object[] { new String[]{ "my arguments args[]" } ....