varargs
- Java course
- Beginner
- Lesson 79/116
- 5 min
Learn flexible parameters with int....
varargs: flexible parameter count
Sometimes you do not know in advance how many arguments will come. By writing int... you declare a parameter that accepts any number of int values. This is called varargs.
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(1, 2, 3); // 6
sum(); // 0Inside the method, nums behaves like an int[]. You can walk it with for-each or read nums.length. A varargs parameter must be the last parameter of the method.
varargs and for-each
To iterate over varargs, for-each is very handy. Because nums behaves like an array; it gives elements one by one.
static int max(int... nums) {
int best = Integer.MIN_VALUE;
for (int n : nums) {
if (n > best) best = n;
}
return best;
}Here Integer.MIN_VALUE is the smallest value an int can hold. So even on an empty call, best starts at a sensible value. After the loop, the largest element is returned.
Practice Flexible sum method
Define a static int method called sum; parameter int... nums. The body should sum all elements and return. Call sum(1, 2, 3, 4) from main and print the result.
Starter code
public class Main {
public static void main(String[] args) {
// Call the method with 1, 2, 3, 4 and print the result
}
// Define the sum method here
}Sample solution
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
// inside main:
System.out.println(sum(1, 2, 3, 4));Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where can a varargs parameter sit in a method?
- Only in the last position
- In the first position
- Only in single-parameter methods
- In any position Correct answer
Explanation: varargs must always be the last parameter; otherwise it is ambiguous.
2 Match call to nums content
| Term | Meaning |
|---|---|
sum(1, 2, 3) |
{1, 2, 3} |
sum() |
{} |
sum(7) |
{7} |
sum(1, 1, 1, 1) |
{1, 1, 1, 1} |
3 Fill in the blank: varargs declaration
static int sum(int____ nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
Explanation: int... declares a varargs.