Part 05 / Topic 4 of 7
Varargs: any number of arguments
Varargs (Type... name) lets a method accept zero, one, or many arguments of one type, without you writing an array literal. Inside the method, the parameter behaves exactly like an array.
static double totalBill(double... prices) {
double total = 0;
for (double price : prices) {
total += price;
}
return total;
}
System.out.println(totalBill(199.0)); // 199.0
System.out.println(totalBill(199.0, 349.0, 90.0)); // 638.0
System.out.println(totalBill()); // 0.0 (zero arguments is fine)
A varargs method can reuse another varargs call directly, because prices is already an array:
static double averageBill(double... prices) {
if (prices.length == 0) {
return 0;
}
return totalBill(prices) / prices.length;
}
A normal parameter can come before varargs, but varargs must always be the last parameter, and a method can only have one varargs parameter.
static void describeOrder(String customer, String... items) {
System.out.println(customer + " ordered " + items.length + " item(s): "
+ String.join(", ", items));
}
describeOrder("Asha", "Rice", "Dal", "Ghee");
// Asha ordered 3 item(s): Rice, Dal, Ghee
describeOrder("Ravi");
// Ravi ordered 0 item(s):
🔍 Going deeper:
public static void main(String[] args)could be writtenmain(String... args)and it would still compile and run the same way —argsis just a varargs parameter the JVM happens to call for you.
Full program: examples/03_coupon_varargs.java.
Done here? The practice set for Part 5 — including the solutions — is on the part page.