Calling Methods with Varargs
You'll learn how to invoke varargs methods in three different ways: with multiple arguments, a single array, or even no arguments at all.
The Three Ways to Call Varargs Methods
Now that you understand varargs methods accept a variable number of arguments, let's explore how flexible they are when you call them.
Passing Multiple Arguments
The most natural way is to pass individual values, separated by commas:
public static void printNumbers(int... numbers) {
for (int num : numbers) {
System.out.print(num + " ");
}
}
// Call with multiple arguments
printNumbers(1, 2, 3, 4, 5); // Output: 1 2 3 4 5
printNumbers(10, 20); // Output: 10 20
Passing an Array Directly
Since varargs are really arrays under the hood, you can pass an actual array:
int[] myArray = {7, 8, 9};
printNumbers(myArray); // Output: 7 8 9
This is useful when you already have data in array form.
Passing Nothing
Here's the cool part—varargs parameters are optional. You can call the method with zero arguments:
printNumbers(); // Valid! Numbers will be an empty array
The method receives an empty array, so the loop simply doesn't execute.
Why This Matters
Think of varargs like ordering pizza toppings: you can name several ("pepperoni, mushrooms, olives"), bring a pre-made list, or order plain cheese with no toppings at all. All three approaches work perfectly.
Key Takeaway: Varargs methods can be called with multiple comma-separated arguments, a single array, or no arguments—giving you maximum flexibility at the call site.