Sub topic 9
Accept Variable Numbers of Arguments
A method is a named group of instructions. An argument is a value you give a method when you call it. A parameter is a name the method uses for an incoming value.
Sometimes you do not know how many values a method will need. A variable-length argument list, or varargs, lets a method accept zero or more arguments of one type. This is useful when, for example, you want to add a list of scores without writing a separate method for each list length.
A method that adds scores
Save this program as ScoreDemo.java:
class ScoreDemo {
static int sum(int... scores) {
int total = 0;
for (int score : scores) {
total += score;
}
return total;
}
static void showTotal(String label, int... scores) {
System.out.println(label + ": " + sum(scores));
}
public static void main(String[] args) {
showTotal("First", 4, 6);
showTotal("None");
int[] saved = {3, 5, 2};
showTotal("Saved", saved);
}
}A class is a group of related code. Here, ScoreDemo contains three methods. The main method is where Java starts the program. The methods are static, so they can be called without creating an object, which is an item made from a class.
To compile and run the program, use:
javac ScoreDemo.java
java ScoreDemoThe output is:
First: 10
None: 0
Saved: 10How the varargs parameter works
In the sum method, int... scores declares a varargs parameter. The three dots after int mean that the method can receive any number of integer values. An integer is a whole number.
Inside the method, Java treats scores as an array. An array is a collection of values of the same type. If the call supplies no scores, the array is empty.
The for loop visits each score in that array. It adds each one to total. The return statement sends the final total back to the caller. If there are no scores, the loop has nothing to visit, so the result stays at zero.
The showTotal method has two parameters:
labelis aString, which holds text. It is a required argument.scoresis a varargs parameter. It can receive zero or more integer arguments.
The void return type means that showTotal does not send back a result. Instead, it prints the label and the result from sum.
Follow the calls
The first call gives showTotal the label First and two scores. The method passes its scores array to sum, which returns 10.
The second call supplies only the required label. Its scores array is empty, so sum returns 0.
The last call passes saved, an existing array, as the scores. When you pass an array this way, the method receives that same array, not a copy. If the method changes an element, the caller can see that change. This example only reads the scores.
Rules to remember
- A method can have only one varargs parameter, and it must be the last parameter.
- Any parameters before it are still required.
- You can pass individual values or an existing array for the varargs parameter. Do not combine an array with extra individual values for that same parameter.
- Use varargs when a variable number of values makes the call clearer. If a method always needs exactly two values, two ordinary parameters may be simpler.
Practice
Exercise
What does showTotal("Round", 2, 3, 4) print? What does showTotal("Round") print?
Show answer
The first call prints Round: 9. The second prints Round: 0 because there are no scores to add.
Exercise
Why can showTotal take a label before its scores, but not declare the label after int... scores?
Show answer
A varargs parameter must be the last parameter in the method declaration.