Varargs (Variable Arguments)
A billing machine adds up however many items you buy: one, three or thirty. If a method to total a bill needed a fixed number of parameters, you'd have to write total(a, b), total(a, b, c) and so on. Varargs (variable arguments) let one method accept any number of arguments of the same type, written with three dots: int... prices.
Any Number of Arguments
public class Bill {
static int total(int... prices) {
int sum = 0;
for (int p : prices) {
sum += p;
}
return sum;
}
public static void main(String[] args) {
System.out.println(total(340));
System.out.println(total(340, 165, 190));
System.out.println(total());
System.out.println(total(new int[]{10, 20}));
}
}340
695
0
30How it works
int... pricesmeans "zero or moreints".- Inside the method,
pricesis an ordinaryint[]. Java collects the arguments into an array for you, so the for-each loop works as usual. - Line 13 calls it with no arguments:
pricesis an empty array, so the total is 0. - Line 14 passes an array directly, which is also allowed.
Try it yourself: write average(int... values) that returns the average as a double. What should it do with no values?
The Rules
- A method can have only one varargs parameter.
- It must be the last parameter.
public class Receipt {
static void print(String shop, int... prices) {
int sum = 0;
for (int p : prices) sum += p;
System.out.println(shop + ": " + prices.length + " items, Rs. " + sum);
}
public static void main(String[] args) {
print("Fresh Mart", 340, 165, 190);
}
}Fresh Mart: 3 items, Rs. 695Fixed parameters come first and take the first arguments; everything left over goes into the varargs array. Putting varargs anywhere else doesn't compile:
V.java:2: error: varargs parameter must be the last parameter
static int sum(int... nums, String label) { return 0; }
^Java Uses Varargs Everywhere
| Method | Declared roughly as |
|---|---|
System.out.printf(format, values...) | printf(String format, Object... args) |
String.format(...) | format(String format, Object... args) |
List.of(...) | of(E... elements) (plus fixed-size versions) |
Arrays.asList(...) | asList(T... a) |
Math.max? | No: only two parameters; use a loop or streams for more |
Common Mistakes
Forgetting that no arguments is allowed. total() gives an empty array; code that reads prices[0] will crash.
Overloading with varargs. show(int a) and show(int... a) both match show(5); Java picks the fixed one, which surprises readers. Avoid such pairs.
Passing null. total(null) makes prices itself null, and the loop throws NullPointerException.
Practice
- Easy: Write
static int max(int first, int... rest)that returns the largest value. - Harder: Write
static String join(String separator, String... parts)that joins the parts with the separator, without usingString.join.
Key Takeaways
Was this tutorial helpful?