Varargs is a helper syntax and it enables use of variable number of arguments in a method call. In method definition variable aruguments are indicated by elipsis (…) and is called as ‘variable arity method’ and ‘variable arity parameter’ in java language specification. While invoking the varargs method we can use any number of arguments of type specified and separated by comma.
FormalParameterList: LastFormalParameter FormalParameters , LastFormalParameter FormalParameters: FormalParameter FormalParameters , FormalParameter FormalParameter: VariableModifiers Type VariableDeclaratorId VariableModifiers: VariableModifier VariableModifiers VariableModifier VariableModifier: one of final Annotation LastFormalParameter: VariableModifiers Type...opt VariableDeclaratorId FormalParameter
In the above note LastFormalParameter gives the elipsis for varargs.
Following is quoted from java language specification and gives information about what is varargs,
If the method being invoked is a variable arity method (ยง8.4.1) m, it necessarily has n > 0 formal parameters. The final formal parameter of m necessarily has type T[] for some T, and m is necessarily being invoked with k >= 0 actual argument expressions.
If m is being invoked with kn actual argument expressions, or, if m is being invoked with k != n actual argument expressions and the type of the kth argument expression is not assignment compatible with T[], then the argument list (e1, … , en-1, en, …ek) is evaluated as if it were written as (e1, …, en-1, new T[]{en, …, ek}).
package com.javapapers.corejava; public class VarArgSample { static int sum(int i, int... marks) { int total = 0; for (int mark : marks) { total = total + mark; } return total; } public static void main(String[] args) { //invoking with variable arguments System.out.println(sum(1, 2, 3)); //same invocation using an array int arr[] = {2,3}; System.out.println(sum(1, arr)); } }
When invoking with variable arguments, compiler matches the argument list from left-to-right with the formal parameters. Once initial set of parameters are matched, then whatever arguments are remaining are constructed as an array and passed to the method. In the given example, value ‘1’ is passed as argument for variable ‘i’ then there are no other arguments remaining except varargs. So the remaining values ‘2, 3’ are constructed as array and passed as parameter. This is how the dynamism is achieved.
Things are just syntactic since once we compile the source changes into array in bytecode. Following is a snapshot from bytecode compiled from the above source.
In bytecode,
15 invokestatic com.javapapers.corejava.VarArgSample.sum(int, int[]) : int [32]
Variable arguments was introduced long long ago in JDK 1.5 But how did we did the same thing before that? We used java array or collections and to some extent we used method overloading.
When we use method overloading we will not be able to achieve complete variability. Like the below we need to write multiple methods and I don’t think will scale enough.
static int sum(int i, int j){ return i + j; } static int sum(int i, int j, int k){ return i + j + k; }
We can implement the same use case as follows using java array and that is how we achieved variable arguments before varargs.
package com.javapapers.corejava; public class VarArgSample { static int sum(int i, int marks[]) { int total = 0; for (int mark : marks) { total = total + mark; } return total; } public static void main(String[] args) { //invocation using an array int arr[] = {2,3}; System.out.println(sum(1, arr)); } }
Though I didn’t measure performance, I guess that there is no significant overhead in using varargs.
As stated above java compiler removes elipsis (…) and replaces it with an array in bytecode. JVM is not aware of varargs and so when we use reflection there is no provision to pass variable arguments and we need to construct an array and pass it.
Some example use of varargs can be found in Oracle’s JDK in reflection and formatting.
In java.lang.Class we can find multiple methods using varargs and following is a sample:
public Method getMethod(String name, Class>... parameterTypes) throws NoSuchMethodException, SecurityException { checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader()); Method method = getMethod0(name, parameterTypes); if (method == null) { throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); } return method; }
In java.io.PrintStream we have methods using varargs and following is a sample.
public PrintStream printf(String format, Object ... args) { return format(format, args); }
We can use the above as,
package com.javapapers.corejava; public class VarArgSample { public static void main(String[] args) { System.out.printf( "%25s %n %10s ", "Hello World!", "Java Varargs: Variable Arguments."); } }
Comments are closed for "Java Variable Arguments".
thank you very much, this is very helpful.
Hi Joe,
This article is easily understandable. I am reading most of your article and most of the articles are very nice and depth as well.
thanks alot,
Thanks joe.. i know abt it earlier but not to this depth.. ur blogs are clear and simple and techie as well best wishes.. plz continue the good work
Joe.. Congratulations on a brilliant post.
Hi Joe,
Do you have any ideas in starting articles on web technologies?
Nice1 joe
lovely article,
I use collection or map to achieve this.
thanks for the post.
very helpful super like
Good one , Joe!!
hi joe,
awsome examplanation…
thanks..
Thank u so much! very nice post!
very very nice……
very nice explaination……
very nicely presented and informative
Hello,
It seems that “int i” is unused in Varargs Sample. Is this bug?
One interesting thing about varargs is that if you invoke sum(1), then compiler will automatically insert an empty varargs array for you.
Good work Joe. keep it up.
nice one joe.. keep updating, but if u update more in a programmatic way, it will be very helpful. Only programs with some explanation if it required. Thanks..
Provide more information
I am following you since long and love your blogs, Really appreciates your effort.
who calls the main method
I immensely like your website, thanx a tonne for sharing the sea of knowledge u have.. !!
hai joe. it is easy methode show you and i want program for var-args that display sum of +ve numbers and -ve numbers separtly
Thanks for clearing this magic :)
Sir, what is the meaning of “int… marks” three dots after int, will you please explain it? Thanks.
this blog is fabulous…………!!!!!
sir,i just want a depth of java……….?
lovely post.. thanks..!
thanks
From WUXI CHINA
“Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.” B’coz on overloading the latest IDEs report an error “The method methodName is ambiguous for the type ClassName…” eventhough the class gets compiled and run without any error.
Hi Sir,
Thanks a lot,It is very easy to understand now.
Your explanation about var- args is very lear and important.
again THANKS
thanxxx a lot….
Joe,
I really like these articles. Keep up the good work!
Regards,
Steve
What is the difference between Varargs and array , why they had introduced Varargs if we have array data type.
please give me an example in varargs that acceps one string argument and one int varargs …
how can i get the value from user….
Hello Joe!!
can you give me the details about everything asked in this problem like abstract, inner class, outer class….everything
problem is here!!!
1. Develop code that declares classes (including abstract and all forms of nested classes), interfaces,
and enums, and includes the appropriate use of package and import statements (including static
imports).
Ur explanation is very clear & simple.It was really helpfull.Thanks a lot.