سؤال

I am new to Java and I'm learning it. I have a question regarding the statement

public static void main(String args[])

I understand all of it what it means. My question is regarding the String args[] part.

String args[] declares a parameter for method main() named args which is an array of instances of the class String.

So can I write anything in place of args[]? Like String pqrs[] or String abc[] or do I have to use args[] as a keyword?

I'm just curious to know how this works?

هل كانت مفيدة؟

المحلول

Using args is just a convention, all of the following would be fine and compile:

public static void main(String args[])

public static void main(String abc[])

public static void main(String anythingElse[])

However; there is annother (arguably more important) convention you are ignoring that will trip you up down the road.

Its usually

public static void main(String[] args)

Doing it the other way round will work, but is confusing because the general assumption is

TypeDefinition variableName

What is the type, is it a String? No, no it is not, its an array of strings, which we represent by String[]. Is the variable name args[]. No its just args

نصائح أخرى

Yes, you can change the name to the one you want, because, at the end, the args name is just a convention.

The signature of the method public static void main, has an argument which is String[], and the name of the variable is up to you.

You can have either:

public static void main(String args[])

Or

public static void main(String arguments[])

Even this:

public static void main(String iAmAnArray[])

What you cannot have is something like this:

public static void main(List<String> iAmAList)

Because List is not part of the signature of the method main.

Short answer yes. I just tried it. args[] is an array. So like most objects declared in a java application you have the freedom to name them. Example

int i = 4; 

I could change the "i" to "j" or "k" and it would still perform the same function. I hope this clears that up for you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top