Sub topic 11
Arrays and Variable-Arity Methods
A method sometimes needs to accept a list of values, but the caller does not know how many values there will be. For example, one call might add two scores, while another adds five.
A variable-arity parameter, or varargs parameter, lets a method accept zero or more values of the same type. Java puts those values into an array for the method to use.
Declare a varargs parameter
A parameter is a variable that receives a value when a method is called. An argument is a value supplied in that call.
Here is a varargs parameter in a method declaration:
static int sum(int... values)
The three dots after int mean that values is a varargs parameter. Inside the method, values is an int[] array. The method can use values.length, read elements by index, or use a loop to visit them.
The caller can supply zero, one, or many int arguments:
sum()supplies no values.sum(4)supplies one value.sum(4, 6, 8)supplies three values.
The caller can also pass an existing int[] array. The method still receives an array either way.
Add scores with varargs
This program adds scores. It also shows a method with a regular parameter before its varargs parameter.
Save the program in a file named Scores.java.
public class Scores {
static int sum(int... values) {
int total = 0;
for (int value : values) {
total = total + value;
}
return total;
}
static void printScores(String name, int... scores) {
int total = sum(scores);
System.out.println(name + ": " + total);
}
public static void main(String[] args) {
int[] saved = {3, 5, 7};
System.out.println(sum());
System.out.println(sum(4));
System.out.println(sum(4, 6, 8));
System.out.println(sum(saved));
printScores("Mia", 2, 4);
printScores("Lee");
printScores("Ari", saved);
}
}Run these commands in the folder containing the file. javac compiles the program, and java runs it.
javac Scores.java
java ScoresThe output has these lines, in order:
| Output | Why |
|---|---|
| `0` | No values were supplied, so the total stays at zero. |
| `4` | The only value is `4`. |
| `18` | The values are `4`, `6`, and `8`. |
| `15` | The existing `saved` array contains `3`, `5`, and `7`. |
| `Mia: 6` | `Mia` is the name; `2` and `4` are the scores. |
| `Lee: 0` | `Lee` is the name, and there are no scores. |
| `Ari: 15` | `Ari` is the name, and `saved` supplies the scores. |
Look at printScores("Mia", 2, 4). The first argument goes to the regular name parameter. Java gathers the remaining arguments into the scores array.
Inside printScores, the call sum(scores) passes that array to another varargs method. The values do not need to be listed again.
What happens when you call the method?
When a caller supplies individual values, Java creates an array containing those values. For sum(4, 6, 8), the method receives an array with three elements.
When a caller supplies no values, Java creates an empty array. It has length zero. That is why the loop in sum() runs zero times and the method returns 0.
When a caller passes an existing array, Java passes that array instead of making a new array for the call. For example, sum(saved) receives the same array that saved refers to.
The argument type must fit the parameter. An int... parameter accepts int values or an int[] array. An array of another type, such as String[], cannot be passed in its place.
You also cannot mix an existing array and extra values in the same varargs part of a call. For example, sum(saved, 8) does not compile. The call must supply either individual int values or one int[] array.
Rules for declarations
A method can have regular parameters as well as a varargs parameter. Follow these two rules:
- A method can have only one varargs parameter.
- The varargs parameter must be the last parameter.
The declaration printScores(String name, int... scores) is valid because scores comes last. A declaration with int... scores before String name is not valid.
The dots belong in the parameter declaration. Inside the method, use the parameter name as an ordinary array name, such as scores.length or scores[0].
A varargs parameter and an array parameter of the same element type have the same parameter type. For example, int... values and int[] values both describe an int[] parameter. You cannot declare two methods that differ only by using those two forms.
Changes to an existing array
A method can change the elements of the array it receives. If the caller passed an existing array, those changes are visible to the caller.
This happens because an array variable holds a reference, which is a way to refer to an array object. Java passes a copy of that reference to the method. Both references still point to the same array.
The next program changes the first word it receives. It also handles an empty array and a missing array.
Save it as Words.java.
public class Words {
static void changeFirst(String... words) {
if (words == null) {
System.out.println("No array");
return;
}
System.out.println("Count: " + words.length);
if (words.length > 0) {
System.out.println("First: " + words[0]);
words[0] = "changed";
}
}
public static void main(String[] args) {
String[] original = {"red", "blue"};
changeFirst(original);
System.out.println("After: " + original[0]);
original[0] = "red";
changeFirst(original.clone());
System.out.println("After clone: " + original[0]);
changeFirst();
changeFirst((String) null);
changeFirst((String[]) null);
}
}Compile and run it:
javac Words.java
java WordsThe first call passes original. The method changes its first element, so After: changed appears in the output.
The program then resets the first element to "red" and passes original.clone(). The clone method creates a separate array with the same elements. This time, changing the first element of the copy does not change original, so the program prints After clone: red.
For an array of object references, a clone copies the references, not the objects they point to. It protects the array slots from changes, but it does not make copies of those objects.
Empty arrays and `null`
An empty array is not the same as null. The value null means there is no array object to use.
In Words, these calls are different:
changeFirst()passes an empty array. The method printsCount: 0.changeFirst((String) null)passes one value: a nullStringreference. The array has length one, so the method printsCount: 1andFirst: null.changeFirst((String[]) null)passes a null array reference. The method printsNo arrayand returns.
The forms (String) null and (String[]) null are casts. A cast tells Java which type to treat a value as. Here, the casts make clear whether null is one word or the whole array.
Writing changeFirst(null) can cause a compiler warning because it is easy to misunderstand. Java treats it as a null array in this call. Use an explicit cast when you mean to pass null.
The check in changeFirst matters because reading words.length when words is null would cause a NullPointerException. That is a runtime error caused by trying to use a missing object.
When to use varargs
Use varargs when callers naturally have a small, changing number of values to pass. A method such as sum(4, 6, 8) is easy to read, and a caller with an existing array can still use sum(saved).
Use a regular array parameter when the method is meant to take one array as a single required input. The method body can work with either form as an array; the main difference is how callers may write the call.
When designing either form, decide whether the method may change the array. If it accepts null, decide what that means and check for it before using the array.
Exercise
What does sum() return in the Scores program, and why?
Show answer
It returns 0. Java supplies an empty array, so the loop does not change the starting total.
Exercise
If int[] numbers = {2, 3};, can you call sum(numbers, 4)? Why?
Show answer
No. The varargs arguments must be individual int values or one int[] array, not an array followed by another value.
Exercise
In Words, what is the difference between changeFirst((String) null) and changeFirst((String[]) null)?
Show answer
The first call passes an array containing one null value. The second passes a null array reference.