Sub topic 9
Accept Variable Numbers of Arguments
Sometimes a method needs to accept a list of values, but the caller does not know how long the list will be. For example, a method that adds scores might need to handle one score, several scores, or none.
Java provides varargs, short for variable-length arguments, for this case. A varargs parameter lets a caller pass zero or more values of the same type.
An argument is a value supplied in a method call. A parameter is the variable in the method declaration that receives it.
Declare and call a varargs method
Write three dots after the type to declare a varargs parameter. In int... values, the parameter is named values and accepts integers.
Save this program as VarargsDemo.java:
class VarargsDemo {
static int sum(int... values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(5));
System.out.println(sum(4, 5));
System.out.println(sum(6, 7, 8));
int[] stored = {4, 5, 6};
System.out.println(sum(stored));
}
}Compile and run it:
javac VarargsDemo.java
java VarargsDemoThe output is:
0
5
9
21
15The first call passes no values. The loop does not run, so the method returns the starting total of 0. The next calls pass one, two, and three values.
The last call passes an array, which is a fixed-size group of values of the same type. Here, stored is an array of three integers.
What happens inside the method
Inside sum, the parameter values is an array of integers. When you call sum(4, 5), Java creates an array holding 4 and 5 for that call. When you call sum(), Java creates an empty array.
The loop in the example is an enhanced for loop. It takes each value from the array, one at a time, and stores it in the variable value. The loop body adds that value to total.
You can also use array features with a varargs parameter:
values.lengthis the number of values in the array.values[0]is the first value, if there is one.values[1]is the second value, if there is one.
Array positions start at zero. Do not use values[0] until you know the array has at least one value. Otherwise, the program reports an error while it runs.
Combine required and variable arguments
A method can have regular parameters before its varargs parameter. The regular parameters still need arguments.
Save this program as RequiredDemo.java:
class RequiredDemo {
static void report(String label, int... scores) {
int total = 0;
for (int score : scores) {
total += score;
}
System.out.println(label + ": " + scores.length
+ " scores, total " + total);
}
static int addAtLeastOne(int first, int... rest) {
int total = first;
for (int value : rest) {
total += value;
}
return total;
}
public static void main(String[] args) {
report("Group", 2, 6);
report("Empty group");
System.out.println(addAtLeastOne(4, 5, 6));
System.out.println(addAtLeastOne(4));
}
}After you compile and run it, the output is:
Group: 2 scores, total 8
Empty group: 0 scores, total 0
15
4In report("Group", 2, 6), the string "Group" goes to label. The integers 2 and 6 go into the scores array. In report("Empty group"), the required label is present, but the scores array is empty.
The addAtLeastOne method uses a regular int parameter to require one number. Its rest parameter can still receive zero or more additional numbers. A call with no arguments, such as addAtLeastOne(), will not compile.
A varargs parameter must be the last parameter in its method declaration. A method can have only one varargs parameter. If more than one group of values needs to vary in length, consider passing separate arrays instead.
Passing an existing array
When a call supplies an existing array to a varargs parameter, Java uses that array; it does not make a copy. A change to an element inside the method is therefore visible to the caller.
Save this program as ArrayChangeDemo.java:
class ArrayChangeDemo {
static void clearFirst(int... values) {
if (values.length > 0) {
values[0] = 0;
}
}
public static void main(String[] args) {
int[] scores = {7, 8};
clearFirst(scores);
System.out.println(scores[0]);
int number = 7;
clearFirst(number);
System.out.println(number);
}
}The output is:
0
7The first call passes the existing scores array. The method changes its first element to 0.
The second call passes the individual value of number. Java creates an array for that call, and the method changes an element in that new array. The caller’s number remains 7.
The length check in clearFirst also makes clearFirst() safe: an empty array has no first element to change.
Watch for null arrays
An empty array is not the same as null. The value null means there is no array. An exception is an error reported while a program runs. Trying to read the length of a null array or loop through it causes an exception.
For example, the earlier call sum() passes an empty array and returns 0. In contrast, sum((int[]) null) passes a null array. The loop in sum then fails because there is no array to read.
With a varargs parameter of a reference type, such as String..., the array and its elements can be null. If a method named show has only a String... parameter, these calls mean different things:
show((String) null)passes an array with one null element.show((String[]) null)passes a null array.
Avoid passing null unless the method explains how it handles it. An empty call, such as show(), is clearer when you mean “no values.”
Varargs and overloaded methods
Overloading means giving methods the same name but different parameter lists. A fixed-parameter method and a varargs method can share a name.
Save this program as ChoiceDemo.java:
class ChoiceDemo {
static String choice(int first, int second) {
return "fixed pair";
}
static String choice(int... values) {
return "varargs";
}
public static void main(String[] args) {
System.out.println(choice(2, 3));
System.out.println(choice(2, 3, 4));
System.out.println(choice());
}
}The output is:
fixed pair
varargs
varargsFor choice(2, 3), Java uses the fixed two-parameter method. The other calls do not fit that method, so they use the varargs method.
Be careful when adding overloads. For example, if one method accepts int... and another with the same name accepts String..., a call with no arguments fits both. Java cannot choose between them, so the call will not compile. Different method names can make the choice clearer.
You also cannot declare both sum(int... values) and sum(int[] values) in the same class as separate overloads. For this purpose, Java treats both parameter types as int[].
Choose varargs when they make calls clearer
Varargs work well when callers often have a small number of separate values, as with sum(4, 5, 6). They also let callers pass an array they already have.
Use a regular array parameter when passing a collection as one array is the main way callers will use the method. Whichever form you choose, explain what happens with no values, a null array, and any changes to array elements.
Practice
Exercise
Using the sum method from the first example, what do sum() and sum(3, 4, 5) return?
Show answer
They return 0 and 12. The first call gives the method an empty array; the second gives it three values to add.
Exercise
Why does addAtLeastOne(4) compile, but addAtLeastOne() does not?
Show answer
The required first parameter receives 4 in the first call. The rest array may be empty, but first must have an argument.
Exercise
If an existing int[] is passed to a varargs method and the method changes its first element, can the caller see the change?
Show answer
Yes. The method receives the existing array, not a copy of it.