Introduction to Varargs Syntax
What You'll Learn
You'll discover how to write methods that accept a flexible number of arguments using Java's varargs (variable arguments) feature.
The Core Idea
Imagine you want to write a method that calculates the sum of numbers, but sometimes you need to add 2 numbers, sometimes 5, sometimes 10. Without varargs, you'd need to write multiple overloaded methods or pass an array. Varargs solves this elegantly by letting one method handle any number of arguments of the same type.
The Syntax
The varargs syntax uses three dots (...) after the type name:
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
Now you can call this method with any number of arguments:
sum(5); // One argument
sum(1, 2, 3); // Three arguments
sum(10, 20, 30, 40); // Four arguments
sum(); // Zero arguments (numbers will be an empty array)
How It Works
Behind the scenes, Java treats the varargs parameter as an array. The method int... numbers is essentially int[] numbers, but the caller doesn't need to create the array explicitly—Java does it automatically.
Important Rules
- The varargs parameter must be the last parameter in the method signature
- You can only have one varargs parameter per method
- You can mix regular parameters with varargs:
void process(String label, int... values)
Key Takeaway: Varargs syntax (Type... name) allows methods to accept zero or more arguments of the same type, making your methods more flexible without requiring explicit array creation by the caller.