Wednesday, October 14, 2009

Varargs in Java

What is varargs ?

varargs - Variable arguments supported in Java from JDK1.5 and higher.
For example you want to specify variable argument in constructor or method you can do it in following ways:

1) Constructor:
public Employee(String firstName, String lastName, String... address);
Note String... is vairable argument.

2) Method:
public int maximum(int first, int... rest);
So variable argument can be of any type.

How JVM interprets ?

When you specify a variable-length argument list, the Java compiler
essentially reads that as “create an array of type ”.
So if you typed:

public Employee(String firstName, String lastName, String... address);

However, the compiler interprets this as:

public Employee(String firstName, String lastName, String[] address);

How to read varargs?

So you can read it as a array directly.
public int maximum(int first, int... rest) {
int max = first;
for (int i : rest) {
if (i > max)
max = i;
}
return max;
}

How to call Varargs method:

If the method is:
public int maximum(int first, int... rest);

It can be called in following ways:
int max = maximum(9, 4);
int max = maximum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int max = maximum(18, 8, 78, 29, 19889, -908);

Classic example of varargs is System.out.printf(String... String);

Varargs Limitations:

1) There can be only one varargs as parameter.
2) varargs should be the last parameter in the list.