Varargs: Handling Variable Arguments
Sometimes you want to create a method, but you don't know exactly how many inputs the user will provide. For example, a method that adds numbers could take 2 numbers, or it could take 20.
Instead of creating 20 different methods (overloading), Java gives us Varargs (Variable Arguments).
1. The Syntax: The Three Dots (...)
To define a varargs parameter, you follow the data type with an ellipsis (three dots).
public static void printNames(String... names) {
// Inside the method, 'names' behaves exactly like an array!
}
2. How It Works
When you call a varargs method, Java automatically gathers all the arguments you passed and puts them into an array for you.
public class VarargsDemo {
public static void main(String[] args) {
// You can pass as many arguments as you want
displayFruits("Apple", "Banana");
displayFruits("Orange", "Mango", "Grape", "Pineapple");
displayFruits(); // You can even pass zero arguments!
}
public static void displayFruits(String... fruits) {
System.out.println("Printing " + fruits.length + " fruits:");
for (String f : fruits) {
System.out.print(f + " ");
}
System.out.println("\n---");
}
}
3. The Rules of Varargs
There are two strict rules you must follow when using varargs in a method:
- Only One Vararg: A method can only have one variable argument parameter.
- The "Last Place" Rule: The varargs parameter must be the last parameter in the method signature.
// ✅ VALID
public void setup(int id, String... roles) {}
// ❌ INVALID (Vararg must be last)
public void setup(String... roles, int id) {}
// ❌ INVALID (Only one vararg allowed)
public void setup(int... ids, String... roles) {}
4. Why Use Varargs?
Varargs make your code more flexible and cleaner to call. A great example of a built-in varargs method is System.out.printf(). It takes a string first, and then an unlimited number of variables to fill the placeholders!
💻 Full Practical Example: The Infinite Adder
Copy this code to see how to build a flexible calculator:
public class Calculator {
public static void main(String[] args) {
int sum1 = sumAll(5, 10, 15);
int sum2 = sumAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
public static int sumAll(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
}
💡 Challenge: The String Joiner
Write a method called joinWords(String... words).
- The method should take any number of strings.
- It should return a single String that joins them all together with a space in between.
- Bonus: If no words are passed, return "No words provided".