Java Variable Arguments

Last modified on August 1st, 2014 by Joe.

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.

Varargs Formal Syntax

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}).

Varargs Sample

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));
	}
}

How Varargs Works?

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] 

What was there before variable arguments?

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.

Varargs Gotchas

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.

JDK’s use of Varargs

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 on "Java Variable Arguments"

  1. Jirka Pinkas says:

    thank you very much, this is very helpful.

  2. Srinivasan says:

    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,

  3. sivarani says:

    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

  4. Ranga Karanam says:

    Joe.. Congratulations on a brilliant post.

  5. Praveen Kumar Jayaram says:

    Hi Joe,

    Do you have any ideas in starting articles on web technologies?

  6. Dharmesh says:

    Nice1 joe

  7. Anonymous says:

    lovely article,
    I use collection or map to achieve this.
    thanks for the post.

  8. Lalit says:

    very helpful super like

  9. Srikanth S says:

    Good one , Joe!!

  10. parthimahesh says:

    hi joe,
    awsome examplanation…
    thanks..

  11. Rashi Coorg says:

    Thank u so much! very nice post!

  12. hemanth says:

    very very nice……

  13. RAM KRISHAN says:

    very nice explaination……

  14. mahesh says:

    very nicely presented and informative

  15. konrad says:

    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.

  16. Gootam says:

    Good work Joe. keep it up.

  17. naresh says:

    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..

  18. Vema says:

    Provide more information

  19. Bhanu Pratap says:

    I am following you since long and love your blogs, Really appreciates your effort.

  20. Anonymous says:

    who calls the main method

  21. Vick says:

    I immensely like your website, thanx a tonne for sharing the sea of knowledge u have.. !!

  22. ram says:

    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

  23. linus says:

    Thanks for clearing this magic :)

  24. A H KHAN says:

    Sir, what is the meaning of “int… marks” three dots after int, will you please explain it? Thanks.

  25. akshaya says:

    this blog is fabulous…………!!!!!
    sir,i just want a depth of java……….?

  26. Shivkant Pandey says:

    lovely post.. thanks..!

  27. Anonymous says:

    thanks
    From WUXI CHINA

  28. Way says:

    “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.

  29. Vijay Malik says:

    Hi Sir,

    Thanks a lot,It is very easy to understand now.
    Your explanation about var- args is very lear and important.
    again THANKS

  30. Aasif Ali says:

    thanxxx a lot….

  31. Steve says:

    Joe,

    I really like these articles. Keep up the good work!

    Regards,
    Steve

  32. Anonymous says:

    What is the difference between Varargs and array , why they had introduced Varargs if we have array data type.

  33. Nisha says:

    please give me an example in varargs that acceps one string argument and one int varargs …
    how can i get the value from user….

  34. Shivi says:

    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).

  35. Anonymous says:

    Ur explanation is very clear & simple.It was really helpfull.Thanks a lot.

Comments are closed for "Java Variable Arguments".