Java 8 varargs on main function signature [duplicate] - java

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

Related

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

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.

What are difference in different notations of String array in main method?

I've used three types of notation while passing argument to main method in java.
public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)
Can anyone tell me the difference between above? Someone has used terms packed and non-packed data for explanation of first two, what are they, and is it related to these?I think first two is somewhat related to coding convention. Am I right?
There is no actual difference, the variants are due to the different ways you can define an array in java syntax.
The standard way to define and array
String[] args
C/C++ style exist from historical reasons
String args[]
Varargs style (When do you use varargs in Java?)
String… args
All will compile to the same bytecode.
I would stick with
public static void main(String[] args)
First two are same.
Infact all three are same at base. But the third kind is called as varargs and has a special purpose which is that it can be used as an optional parameter in methods. For example if you have a method that requires parameters int x, String... y then even you call the parameter without passing String... y as parameter argument, the code will compile. More information here: Methods, Optional Parameters and/or Accepting multiple Data Types
Also check this: Java varags method param list vs. array

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)

Explanation of 'String args[]' and static in 'public static void main(String[] args)' [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 7 years ago.
How can you explain very well, to a beginner, the meaning of String args[] and the use of static in the following excerpt?
class FirstApp {
public static void main(String[] args) {
...
}
}
I would break up
public static void main(String args[])
in parts:
public
It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in your current class.
static
When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
void
Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
main
It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
String args[]
These are the arguments of type String that your Java application accepts when you run it.
I would point a beginner to the Wiki article on the Main function, then supplement it with this.
Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().
String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.
public static void main(string [] args)
public -its the access specifier means from every where we can access it;
static -access modifier means we can call this method directly using a class name without creating an object of it;
void- its the return type;
main- method name
string [] args - it accepts only string type of argument... and stores it in a string array
public : it is a access specifier that means it will be accessed by publically.
static : it is access modifier that means when the java program is load then it will create the space in memory automatically.
void : it is a return type i.e it does not return any value.
main() : it is a method or a function name.
string args[] : its a command line argument it is a collection of variables in the string format.
If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :
public static void main(String[] args) {
...
}
Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.
Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.
Then you can spend some time talking about meaning of these IMHO.
You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.
public static void main(String ...args) {
//...
}
I just thought I'd chip in on this one. It's been answered perfectly well by others though.
The full main method declaration should be :
public static void main(final String[] args) throws Exception {
}
The args are declared final because technically they should not be altered. They are console parameters given by the user.
You should usually specify that main throws Exception so that stack traces can be echoed to console easily without needing to do e.printStackTrace() etc.
As for Array Syntax. I prefer it this way. I suppose that it's a little bit like the difference between french and english.
In English it's "a black car", in french it's "a car black".
Which is the important noun, car, or black?
I don't like this sort of thing :
String blah[] = {};
What's important here is that it's a String array, so it should be
String[] blah = {};
blah is just a name. I personally think it's a bit of a mistake in Java that arrays can sometimes be declared in that manner.
To keep beginner attitude you can explain that all the command line is automatically split into an array of String (the String[]).
For static you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class
So main is static, because it is the only way to find it (linked in its own class) in a jar.
after you look at coding, and your job begin .
The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

Why doesn't Java's main use a variable length argument list?

I have a question about the syntax of the Java main declaration:
public static void main (String[] args)
Since you can pass a variable number of Strings when invoking the main function, shouldn't this be a variable length argument list rather than an array? Why would a command-line invocation of this method with a list of string parameters even work? (Unless there is behind-the-scenes processing that builds an array with the list of strings and then passes that array to the main method...?) Shouldn't the main declaration be something more like this...? -
public static void main(String... args)
main(String... args) and main (String[] args) are effectively the same thing: What you're getting is a String array. The varargs is just syntactic sugar for the caller.
I guess as you never call main() from code, it wasn't retrofitted when varargs were introduced.
Edit: Actually, scratch that last sentence. main(String... args) is perfectly valid syntax, of course. The two styles are completely interchangeable. This works just fine:
public class Test {
public static void main(String... args) {
System.out.println("Hello World");
}
}
You can declare main either way, and it works just fine. There are no "backward compatibility" or "retrofitting" issues. However, readers of your code may find it distracting, and it is unlikely to improve your program in any way.
The Java Language Specification (third edition) section 8.4.1 says that "If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]".
The specification for how a Java program starts up is in JLS 12.2, which references chapter 5 of the VM spec. The VM spec section 5.2 says that the VM invokes a public class method "void main(String[])". Since the VM spec has no concept of variable arity, a main that was declared using "..." satisfies the requirement.
The main method was designed for Java 1.0.
The "..." syntax was introduced in Java 1.5
It's implemented via an array of the type you defined (my guess, but... if Java 1.4 and 1.5 byte codes are compatible so it must be implemented with arrays).
There is no Java's main method, in fact you can declare the array as a vararg in your main method:
public static void main(String... args) { System.out.println("Hi!"); }
The java main syntax predates varargs, which were only introduced in java 1.5.
Shouldn't the main declaration be something more like this...?
public static void main(String... args)
Actually, that could be done without a problem.
It was String [] args before var args were introduced but nowadays both work.
Well, the 2nd syntax is just a variation of 1st and yes it would be nice but it's not built into Java at this point

Categories

Resources