How does the Java array argument declaration syntax "..." work? - java

I have been writing java for a while, and today I encountered the following declaration:
public static void main(String... args) {
}
Note the "dot dot dot" in the array declaration, rather than the usual bracket []. Clearly it works. In fact I wrote a small test and verified it works. So, I pulled the java grammar to see where this syntax of argument declaration is, but did not find anything.
So to the experts out there, how does this work? Is it part of the grammar? Also, while I can declare function like this, I can't declare an array within a function's body like this.
Anyway, do you know of any place that has this documented. It is curiosity, and perhaps not worth of any time invested in it, but I was stumped.

I believe this was implemented in Java 1.5. The syntax allows you to call a method with a comma separated list of arguments instead of an array.
public static void main(String... args);
main("this", "is", "multiple", "strings");
is the same as:
public static void main(String[] args);
main(new String[] {"this", "is", "multiple", "strings"});
http://today.java.net/article/2004/04/13/java-tech-using-variable-arguments
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

Check out the Java Language Specification, Third Edition, Chapter 8 (Classes). Buried in there is this nugget:
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 method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).
Basically, the last parameter of any method call can have T.... If it has that, it is converted to T[].
So basically, what you have is a fancy way of reproducing the more traditional
String[] args

It is varargs
In simple term its an Array of Member like
public setMembers(Member[] members);
When to use:
Generally while designing API it is good to use when number of argument is not fixed.
Example from standard API of this is String.format(String format,Object... args)
Also See
var-arg-of-object-arrays-vs-object-array-trying-to-understand-a-scjp-self-test

This is called variadic arguments, check here:
http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.23.2C_C.2B.2B.2FCLI.2C_VB.net.2C_and_Java
The official documentation (Java 1.5) is here:
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

It's the so-called varargs syntax. In the method body, you can read the members parameter as it were an array - actually, it /is/ 'just' an array.
However, the magic bit is in calling the method. Before the varargs syntax was introduced, you'd call the method a bit like so:
setMembers(new Members[] {member1, member2, member3});
With the new varargs syntax however, you don't need to explicitly create the array anymore, and you can pass:
setMembers(member1, member2, member3);
This does mean however that a varargs argument has to be the last argument in a method. Something like this is therefore not permitted:
void setMembers(Member ... members, String memberType);
Summarized: It's a bit of syntactic sugar, really. I'm no expert on the inner workings of the Java compiler, but I'm pretty sure that methods calling a method that accept a varargs parameter are rebuilt into methods that build an array of the given type.

You might want to read up on Using Variable Arguments (or varargs) in Java.

It's called varadic argument: A function that takes as many (including zero) arguments as you want.
For example, main("string1", "string2", "string3") is same as main({"string1", "string2", "string3"}) if main is declared as void main(String...args).
See http://www.java-tips.org/blog/java-se/varargs-%E2%80%93-java-50-addition.html

It means you can pass zero or more Member objects to the setMembers() method. In the setMembers method, members will have array semantics.

Variable arguments. Can have 0 or more String arguments.
The function can access the parameters as an array of Strings.

It means that the method accepts a variable number of String arguments. The arguments are treated as an array and so are accessed by subscript, in the order they are passed in.

Related

Comparable Interface (Heap)

This is heapifying the array question and
this is my constructor of the heapcls which extends to Comparable
heapcls(T[] arr,boolean flag){
this(flag);
for (T item : arr) {
this.data.add(item);
}
for(int i=this.data.size()-1;i>=0;i--){
this.downheapify(i);
}
}
public static void main(String[] args) {
int[]arr={7,8,9,5,11,3,10,1,6,2,4,12,0,-1,13};
heapcls<Integer> client=`enter code here`new heapcls<>(arr,false);
}
this statement is giving ," Cannot infer type arguments error"
how should I change my CompareTo(by default function) to rectify the error.
since i havent overridden the bydefault CompareTo function.pls guide me.
The actual issue is that you're trying to pass an int[] to a constructor which has T[] as a parameter. Since the type on the left-hand side of the assignment is heapcls<Integer>, the constructor is supposed to have Integer[] passed to it as an argument.
Type arguments to generic types can't be primitive types and arrays of primitives aren't autoboxed. (Autoboxing an array would require allocating an entire new array.)
It seems like you could fix this just by using Integer[] instead of int[].
I'm not really sure why we get the "cannot infer type arguments" message in cases like this. I think it's a bug with the Java compiler when using the diamond type (i.e. <>) and the arguments to the constructor aren't applicable to any of the declared constructors. (Here's a much more minimal example showing the same issue with the error message: http://ideone.com/wJx16i.)
In any case, your code shouldn't compile, but because you're trying to pass an int[] as an argument to a constructor which effectively has Integer[] as a parameter, not really because the type arguments can't be inferred.
As a side note, class names in Java start with an upper-case character by convention, so your heapcls should be HeapCls (and probably just something like Heap).

Concept of varargs and ambiguity?

Here's an example:
package com.demo;
public class PassArray {
static void vaTest(int... v){
System.out.println("no of args : "+v.length+"contents: ");
for (int x:v){
System.out.println(x+" ");
}
}
static void vaTest(boolean... v){
System.out.println("no of args : "+v.length+"contents: ");
for (boolean x:v){
System.out.println(x+" ");
}
}
public static void main(String args[]){
vaTest(1,2,3);
vaTest(true,false,true);
vaTest();//Error:Ambiguous!
}
}
Can anyone tell me :
I have some Question
1.Why ambiguous error occure ?
2.i have one Varargs parameter just like
int doIt(int a,int b,int c,int... vals)
Why varargs must be declared last ?
What is varargs and ambiguity ?
Since there are two legal method invocations to the call vaTest();, the compiler can't figure out which one to use.
To help it out, you can provide an empty array of the chosen type:
vaTest(new int[] {});
More info is available in the JLS 15.12.2.5. Choosing the Most Specific Method.
Why ambiguous error occure ?
Because you haven't passed any arguments, and both the methods are valid candidate for invocation, as both can be invoked without any argument. The compiler cannot decide onto which method to bind the method call, as there is no parameter type to distinguish between the methods.
Why varargs must be declared last ?
Well, because that's how people who created Java wanted it to be declared. May be they wanted the task for the compiler easy. If the varargs are declared as last parameter, the compiler can just go on to bind all the arguments after the last non-vararg parameter to the vararg parameter. Of course, it would have been possible even if the vararg was allowed somewhere in the middle, but that would require compiler to bind the parameters towards the ends first, or at least some kind of algorithm to find out that there are enough arguments left to bind to the further non-vararg parameters. That would have made the parsing complex, as the compiler binds method argument left-to-right (that would have required some changes). May be language creator thought, adding this feature will not weigh much to justify the changes in how compiler binds the arguments. So, this restriction.
1.Why ambiguous error occure ?
This part has been already answer by other user, nicely.
Why varargs must be declared last ?
Well this is how JAVA is written. The reasonable explanation i can think of is keeping the usual read direction of the parenthesis () which has Associativity: left-to-right, If we are to declare a function like:
public void aFunc(String... args, String x, String y, String z)
If we invoke this function with exactly three arguments:aFunc("arg1", "arg2", "arg3"): Then we have a decision problem: which variable should belong to variable arity parameter args? To know the answer we will have to go from right-to-left, just reverse of the usual order of the parenthesis () associativity.

Java varargs for multiple arguments

Is it considered a good programing idiom to use Java varargs as an optional parameter?
Even more: if I have an interface, and some implementations need the additional parameter, and some don't, is it okay to use varargs in the method signature for the optional parameter?
In Java it is possible to use the following idiom:
public static void x(String ... strings)
which gets an array of strings, possibly empty. You could call it with
x() (empty array), x("1","2","3") etc
Varargs is usually used when you don't know the number of arguments of a "particular type" that the users of the api will like to pass. I don't think there is any problem with that since the user can decide to pass any number of parameter or not to pass any at all. For eg
public class NewClass {
public void print(String... a) {
System.out.println(a);
}
public static void main(String[] args) {
new NewClass().print();
}
}
Doen't hurt. Since you know the type of in the varargs.
I would say no. Using a varargs will allow any number of arguments to be provided for your optional parameter. How will you communicate to people implementing your interface or calling your method that only one value is expected? What should the behavior be when multiple values are provided? These are unnecessary complications.
If your method requires exactly 0 or 1 value for the optional argument, then you should use a language construct that only allows 0 or 1 value to be provided. It would be more appropriate to overload the method signature or allow the optional parameter to be null.
I don't think it is a good idea to use varargs to implement optional parameters.
Animal a = new Dog();
a.speak("bow");
You have no idea looking at the reference in above example what arguments should be applied as you may not know that it is a dog if the animal was extracted from say a List of animals.
As said by #Oli explicit overload is a good approach instead.

What does "..." mean in java? [duplicate]

I have been writing java for a while, and today I encountered the following declaration:
public static void main(String... args) {
}
Note the "dot dot dot" in the array declaration, rather than the usual bracket []. Clearly it works. In fact I wrote a small test and verified it works. So, I pulled the java grammar to see where this syntax of argument declaration is, but did not find anything.
So to the experts out there, how does this work? Is it part of the grammar? Also, while I can declare function like this, I can't declare an array within a function's body like this.
Anyway, do you know of any place that has this documented. It is curiosity, and perhaps not worth of any time invested in it, but I was stumped.
I believe this was implemented in Java 1.5. The syntax allows you to call a method with a comma separated list of arguments instead of an array.
public static void main(String... args);
main("this", "is", "multiple", "strings");
is the same as:
public static void main(String[] args);
main(new String[] {"this", "is", "multiple", "strings"});
http://today.java.net/article/2004/04/13/java-tech-using-variable-arguments
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Check out the Java Language Specification, Third Edition, Chapter 8 (Classes). Buried in there is this nugget:
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 method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).
Basically, the last parameter of any method call can have T.... If it has that, it is converted to T[].
So basically, what you have is a fancy way of reproducing the more traditional
String[] args
It is varargs
In simple term its an Array of Member like
public setMembers(Member[] members);
When to use:
Generally while designing API it is good to use when number of argument is not fixed.
Example from standard API of this is String.format(String format,Object... args)
Also See
var-arg-of-object-arrays-vs-object-array-trying-to-understand-a-scjp-self-test
This is called variadic arguments, check here:
http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.23.2C_C.2B.2B.2FCLI.2C_VB.net.2C_and_Java
The official documentation (Java 1.5) is here:
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
It's the so-called varargs syntax. In the method body, you can read the members parameter as it were an array - actually, it /is/ 'just' an array.
However, the magic bit is in calling the method. Before the varargs syntax was introduced, you'd call the method a bit like so:
setMembers(new Members[] {member1, member2, member3});
With the new varargs syntax however, you don't need to explicitly create the array anymore, and you can pass:
setMembers(member1, member2, member3);
This does mean however that a varargs argument has to be the last argument in a method. Something like this is therefore not permitted:
void setMembers(Member ... members, String memberType);
Summarized: It's a bit of syntactic sugar, really. I'm no expert on the inner workings of the Java compiler, but I'm pretty sure that methods calling a method that accept a varargs parameter are rebuilt into methods that build an array of the given type.
You might want to read up on Using Variable Arguments (or varargs) in Java.
It's called varadic argument: A function that takes as many (including zero) arguments as you want.
For example, main("string1", "string2", "string3") is same as main({"string1", "string2", "string3"}) if main is declared as void main(String...args).
See http://www.java-tips.org/blog/java-se/varargs-%E2%80%93-java-50-addition.html
It means you can pass zero or more Member objects to the setMembers() method. In the setMembers method, members will have array semantics.
Variable arguments. Can have 0 or more String arguments.
The function can access the parameters as an array of Strings.
It means that the method accepts a variable number of String arguments. The arguments are treated as an array and so are accessed by subscript, in the order they are passed in.

What does "..." mean in Java? [duplicate]

I have been writing java for a while, and today I encountered the following declaration:
public static void main(String... args) {
}
Note the "dot dot dot" in the array declaration, rather than the usual bracket []. Clearly it works. In fact I wrote a small test and verified it works. So, I pulled the java grammar to see where this syntax of argument declaration is, but did not find anything.
So to the experts out there, how does this work? Is it part of the grammar? Also, while I can declare function like this, I can't declare an array within a function's body like this.
Anyway, do you know of any place that has this documented. It is curiosity, and perhaps not worth of any time invested in it, but I was stumped.
I believe this was implemented in Java 1.5. The syntax allows you to call a method with a comma separated list of arguments instead of an array.
public static void main(String... args);
main("this", "is", "multiple", "strings");
is the same as:
public static void main(String[] args);
main(new String[] {"this", "is", "multiple", "strings"});
http://today.java.net/article/2004/04/13/java-tech-using-variable-arguments
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Check out the Java Language Specification, Third Edition, Chapter 8 (Classes). Buried in there is this nugget:
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 method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).
Basically, the last parameter of any method call can have T.... If it has that, it is converted to T[].
So basically, what you have is a fancy way of reproducing the more traditional
String[] args
It is varargs
In simple term its an Array of Member like
public setMembers(Member[] members);
When to use:
Generally while designing API it is good to use when number of argument is not fixed.
Example from standard API of this is String.format(String format,Object... args)
Also See
var-arg-of-object-arrays-vs-object-array-trying-to-understand-a-scjp-self-test
This is called variadic arguments, check here:
http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.23.2C_C.2B.2B.2FCLI.2C_VB.net.2C_and_Java
The official documentation (Java 1.5) is here:
http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
It's the so-called varargs syntax. In the method body, you can read the members parameter as it were an array - actually, it /is/ 'just' an array.
However, the magic bit is in calling the method. Before the varargs syntax was introduced, you'd call the method a bit like so:
setMembers(new Members[] {member1, member2, member3});
With the new varargs syntax however, you don't need to explicitly create the array anymore, and you can pass:
setMembers(member1, member2, member3);
This does mean however that a varargs argument has to be the last argument in a method. Something like this is therefore not permitted:
void setMembers(Member ... members, String memberType);
Summarized: It's a bit of syntactic sugar, really. I'm no expert on the inner workings of the Java compiler, but I'm pretty sure that methods calling a method that accept a varargs parameter are rebuilt into methods that build an array of the given type.
You might want to read up on Using Variable Arguments (or varargs) in Java.
It's called varadic argument: A function that takes as many (including zero) arguments as you want.
For example, main("string1", "string2", "string3") is same as main({"string1", "string2", "string3"}) if main is declared as void main(String...args).
See http://www.java-tips.org/blog/java-se/varargs-%E2%80%93-java-50-addition.html
It means you can pass zero or more Member objects to the setMembers() method. In the setMembers method, members will have array semantics.
Variable arguments. Can have 0 or more String arguments.
The function can access the parameters as an array of Strings.
It means that the method accepts a variable number of String arguments. The arguments are treated as an array and so are accessed by subscript, in the order they are passed in.

Categories

Resources