Why Java Only Allows String[] args as Main method Argument? [duplicate] - java

This question already has answers here:
Why we Pass String array as argument to main() method, why not any collection type or wrapper type or primitive type?
(5 answers)
Closed 2 years ago.
Why Java only allows the main method to take argument of the form String[] args? i.e an array of strings
public static void main(String[] args)
And why doesn't Java allow an array of int or double like
public static void main(int[] args)
or
public static void main(double[] args
And why doesn't it allow a single string or int or float rather than array of string? Something like:
public static void main(String args)
or
public static void main(int i)

This is how you would run a java program in a command line:
java YourMainClass
The command line arguments comes after that:
java YourMainClass arg1 arg2 arg3
This would make the args string array contain "arg1", "arg2" and "arg3". If you make the args array an int[], how on earth is arg1 going to be put into an int?
From the JVM's perspective, putting the command line arguments in Strings is the safest option. Anything that the user enters, it is gotta be a bunch of chars.
As per the JLS,
Section 12.1.4:
Finally, after completion of the initialization for class Test (during
which other consequential loading, linking, and initializing may have
occurred), the method main of Test is invoked.
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.

Related

Can main function take a String instead of String[]

public static void main(String[] args)
I know conventionally the main function takes in a parameter args that contains the supplied command line arguments as an array of String objects.
I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer?
If there is a way to specify input for the main function, please provide an example.
Answer to your question: NO
Details:
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html
The java command starts a Java application. It does this by starting a Java runtime environment, loading a specified class, and calling that class's main method.
The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:
public static void main(String[] args)
As you already know that is the method definition of main and you cannot change it. However, you can convert the elements within the args array to any other primitive type considering that it's in a valid format to be converted to the type on the left side of the assignment operator.
There are multiple ways to achieve this, one of which is:
int input = Integer.valueOf(args[0]);
No, your main method cannot take just a String, main method must accept an array of String using array syntax or varagrs syntax, read following JSL §12.1.4. Invoke Test.main
Finally, after completion of the initialization for class Test (during
which other consequential loading, linking, and initializing may have
occurred), the method main of Test is invoked.
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)
So, you can opt for either syntax but not just a String.
Just for your info you can create a method like public static void main(String args) but it wouldn't be regarded as "main" method of the class which JVM looks as the starting point. So, if you want to have a "main" method in your class then you have to choose from either of the above syntax.
Why not a String or an array of Integer?
Not an array of Integer because that array will cover only a subset of possible arguments (You can parse them and get an Integer, but you also need to check if they are Integers otherwise you'll get a NumberFormatException).
Not a string instead of a String array because it's better to have the command arguments separated instead of having them in one big string, in fact, a lot of times you need to handle the command arguments separately.
There's no alternative signature that the VM will recognize as main method. There is only one main signature allowed that is public static void main(String[] args)
I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer?
Yes, you can take any String or Integer as parameter, but that would become a different function main() method instead of the one used by java to start your program. After compilation, java search for public static void main(String[] args){} method to start with. If you change parameters then your program won't run at all. Now using array will cover only particular type of values that array can permit like int[] will only store intvalues, similarly String can have only one value, while you may want to have multiple arguments.
If there is a way to specify input for the main function, please provide an example.
Yes, there are ways to pass argument using command line(for windows) and terminal(for linux/unix).
compile your java program by using javac Filename.java
run java program along with parameters java FileName param1 param2 param3
(param1, param2, param3 are parameters that you want to pass).

Java 8 varargs on main function signature [duplicate]

This question already has answers here:
Why doesn't Java's main use a variable length argument list?
(7 answers)
Closed 6 years ago.
I was converting a Groovy codebase into Java and forgot to change
public static void main(String... args) {
to
public static void main(String args[]) {
and compiled and ran the project all this time only to be surprised only now that this is legal Java 8 code.
I understand that Java 8 Varargs makes it possible for a function to have arbitrary number of arguments, "compacting them into an Array" depending on their position on the method call.
But the way functions with String... args and String[] args are called syntactically differently:
void function1 (String[] args) {}
function1({"one", "two", "three"});
void function2 (String... args) {}
function2("one", "two", "three");
So how is String... args as legal as String args[] when grabbing params from the terminal?
Edit:
azurefrog linked an answer to a different question that is great. I wanted to mention another answer where the comments provide the answer I was looking for:
Why doesn't Java's main use a variable length argument list?
Comment 1: Interesting. Judging by the other answers/comments, I guess this new main declaration syntax was added with Java 1.5. So the Java runtime determines, based on your main method declaration, whether to pass the strings directly to the main or build an array first?
Comment 2: No, it always builds an array. String... args == String[] args, as far as the called method is concerned. The parameter is an array in any case
That's the question I had. Sorry if it was asked poorly.
It's been legal since varargs were added to the language, I believe. The syntax for calling them explicitly differs, sure, but command-line arguments are passed in not by other Java code but "magically."
JLS 12.1.4 specifies this:
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)
As you already said, at compile-time all varargs... are swapped out with arrays[].
Thus the java compiler recognizes your vararg parameters and puts them into an array.
See #Louis_Wasserman 's answer for the JSL quote.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html --- the Java Tutorial

Why is it necessary to have `String[] args` as main() parameter?

I'm not asking what is (String args[]) because that was answered here: What is "String args[]"? parameter in main method Java.
My question is why is it necessary to write it while writing main()?
I had my practical exams, where I faced a problem and realized I hadn't written String args[] while writing public static void main(). But then after writing main(String args[]) the problem was solved. (How and Why I still don't know!)
On that same day I was asked in Viva I was asked - "Is it necessary to write this String args[] while writing main()?" and thanks to the error that occurred I replied "YES" but was left without answer when asked "WHY?".
So I want to know why is it necessary to write String[] args.
From Java Language Specification 12.1.4
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)
(note that you can't have two main methods with String[] and String... in same class, since varargs are simply syntactic sugar which at compilation time will be replaced with arrays so you would end up with two methods handing String[] and one class can't have two methods with same name and parameters)
So when you execute command like
java YourClass foo bar
Java Virtual Machine will place foo and bar parameters in String[] array and will try to pass that array to main method which can accept it as parameter.
This method is also used when command doesn't have any arguments like
java YourType
This decision simplifies our life because we don't need to focus on handling cases where there are two entry points
one for command with arguments
and one where command doesn't have any arguments.
We can simply allow user to pass arguments but if we don't wan to handle them we can simply ignore them.
Also remember that we are allowed to have in our class any method which has proper declaration (and doesn't violate any rules inherited from superclass like widening member visibility - we can't make protected method public), so there is nothing wrong with having
public static void main(){
/*your code*/
}
But you need to realize that this method can't be used as entry point, so if you want to start your application from this method you will need to create proper main method which will execute your main() method:
public static void main(String ...){
main();
}
In Java the entry point has to be a public static void main(String[]) method. This is simply what is called when you run your class. A main() method with no arguments will not be called. If you have no arguments in your command you are merely calling main(String[]) with an array of length 0.
To address the Viva question, the parameter's identifier is used by the compiler only and can be changed, along with the alternate placement of the [] or using String... to specify an array. So it appears to be a technicality, but you can use any of the following:
public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)
public static void main(String[] custom_identifier)
public static void main(String custom_identifier[])
public static void main(String... custom_identifier)
It's for the command arguments. Without them, the JVM would have to perform a check to see if the method contains arguments before attempting to call the method, determining whether it could do main() or main(args) (two syntactically correct methods with different ways to call them)

Two Main methods with different signatures

I have following class.
public class Test {
public static void main(Integer[] args) {
System.out.println("This is not a main");
}
public static void main(String[] args) {
System.out.println("This is the main");
}
}
In here there are two main method which are accept Integer[] and String [] as input argument. My question is how JVM always load second method as main method of this class. Why always consider input argument as array of String?
Because that's what Java always looks for. Java Language Specification, Section 12.1.4:
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
Because Strings are what you're passing into the command line.
the 45 from
myProgram.exe 45
is not an integer. it is a string containing the characters 4 and 5
It just so happens that you can use a string like "45" to represent an integer. It's a little more difficult to do it the other way around.(for the user at least)
Since command line arguments are always Strings.
We always enter command line args as Strings. :)
Aside from what others have mentioned, you can use var-args to implement String array.
public static void main (String ...a)
For further information check this doc
http://docs.oracle.com/javase/tutorial/getStarted/application/
And also
Using int Instead Of String: public static void main (int[] args)
As others have said, the main method will always be called by the JVM with the overload that takes a string array. You are free to make other overloads to that metod if you so wish. You may even call them yourself in your code. It's just that the VM specifically looks for that one overload that takes an array of strings.
This is the only signature recognized by the JVM as THE MAIN METHOD
public static void main(String[] args)
You can have as many overloaded main method as you want BUT only the method with the above signature will be called by the jvm
Command-line arguments are arguments to the main() method which are passed to it at run-time. Since Java uses only String type command-line arguments, the JVM ignores the other main() method which passes Integer.
The signature of the main method in java is public static void main(String[] args) {} and that is what the JVM's classloader loads at the start of the program. The other main with an Integer argument won't be called unless you did it manually inside main. Try modifying your code as shown below and you'll notice that nothing will be called and your program won't print anything.
public class Test {
public static void main(Integer[] args) {
System.out.println("This is not a real main so nothing gets printed");
}
}
Btw, you can write an overloaded main method with any argument that you want. As long as the argument is not String[] or String... which are the same, nothing will start rolling the program.

What does `public static <T> void main(String[] args)` stand for?

What does public static <X> void main(String[] args) stand for? I tried to understand but didn't get. I know about public static void main(String[] arg).
Thanks in advance.
Let's look at each bit in turn:
public - it's a public method, accessible to anything which has access to the class in which this is declared
<X> - this is (somewhat bizarrely) a generic method with an unbound type variable X
static - the method is related to the type in which it's declared, not any specific instance of the type
void - the method doesn't return a value
main - the name of the method
String[] args - a single parameter, of type String[] and called args
main is the entry point used by the JVM. When you run:
java foo.bar.Baz
it will try to find a main method in class foo.bar.Baz. I've never seen a generic main method before, admittedly. For more about generics in Java, read the Java Generics FAQ.
<X> is known as Type Parameter.
This is applicable to the methods, classes, variables, etc.. But its most important use is to make the Collections more type safe.
<X> will mark a certain Type within the main() method.
The whole sentence dissection is as follows:
public - is the access-modifier, means that this method is accessible from anywhere.
<X> - Type Parameter, as mentioned above
void - This method will not return anything
main - Method's name, main() method is the entry point of any pgm in java.
String[] : Array Of String.
args : Array reference variabl of type String.

Categories

Resources