Variable Arguments (Varargs)
Methods with variable number of arguments
Interview Relevant: Understanding varargs syntax and limitations
5 min read
What are Varargs?
Varargs (variable-length arguments) allow you to pass zero or more arguments to a method. Internally, varargs are treated as arrays.
Syntax
returnType methodName(Type... paramName) {
// paramName is treated as Type[]
}
🔑 Key Rules:
- Varargs must be the last parameter
- Only one varargs parameter per method
- Can pass an array or individual values
How Varargs Work
When you call a varargs method, Java creates an array behind the scenes. This means you can use array operations inside the method.
⚠️ Performance Note: Each varargs call creates a new array object. For performance-critical code with fixed argument counts, consider method overloading.
Code Examples
Basic varargs usage with sum method
java
1// Basic varargs method
2public static int sum(int... numbers) {
3 int total = 0;
4 for (int num : numbers) {
5 total += num;
6 }
7 return total;
8}
9
10// Call with varying arguments
11System.out.println(sum()); // 0 (zero args)
12System.out.println(sum(5)); // 5 (one arg)
13System.out.println(sum(1, 2, 3)); // 6 (three args)
14System.out.println(sum(1, 2, 3, 4, 5)); // 15 (five args)
15
16// Can also pass an array
17int[] arr = {10, 20, 30};
18System.out.println(sum(arr)); // 60Combining varargs with other parameters
java
1// Varargs with other parameters
2public static void printAll(String label, int... values) {
3 System.out.print(label + ": ");
4 for (int v : values) {
5 System.out.print(v + " ");
6 }
7 System.out.println();
8}
9
10printAll("Numbers", 1, 2, 3); // Numbers: 1 2 3
11printAll("Empty"); // Empty:
12printAll("Single", 42); // Single: 42
13
14// WRONG: Varargs not last
15// public void wrong(int... nums, String s) {} // Compile error!
16
17// WRONG: Multiple varargs
18// public void wrong(int... a, String... b) {} // Compile error!Real-world varargs examples like printf
java
1// Printf uses varargs
2System.out.printf("Name: %s, Age: %d%n", "Alice", 25);
3System.out.printf("Pi: %.2f%n", 3.14159);
4
5// String.format also uses varargs
6String formatted = String.format("Hello, %s!", "World");
7System.out.println(formatted);
8
9// Custom printf-like method
10public static String format(String template, Object... args) {
11 for (int i = 0; i < args.length; i++) {
12 template = template.replace("{" + i + "}", String.valueOf(args[i]));
13 }
14 return template;
15}
16
17String result = format("User {0} is {1} years old", "Bob", 30);
18System.out.println(result); // User Bob is 30 years oldGeneric varargs and method overloading
java
1// Varargs with generics
2public static <T> List<T> asList(T... elements) {
3 List<T> list = new ArrayList<>();
4 for (T elem : elements) {
5 list.add(elem);
6 }
7 return list;
8}
9
10List<String> names = asList("Alice", "Bob", "Charlie");
11List<Integer> nums = asList(1, 2, 3, 4, 5);
12
13// Method overloading vs varargs
14// Overloading is faster for known argument counts
15public static int max(int a, int b) {
16 return a > b ? a : b;
17}
18
19public static int max(int a, int b, int c) {
20 return max(max(a, b), c);
21}
22
23public static int max(int... numbers) {
24 if (numbers.length == 0) throw new IllegalArgumentException();
25 int max = numbers[0];
26 for (int n : numbers) {
27 if (n > max) max = n;
28 }
29 return max;
30}Use Cases
- Methods that accept any number of arguments
- printf/format style methods
- Utility methods (sum, max, min)
- Collection factory methods
- Logging frameworks
- Builder pattern methods
Common Mistakes to Avoid
- Placing varargs before other parameters
- Having multiple varargs in same method
- Ambiguous overloading with varargs
- Null handling issues
- Performance overhead with many calls
- Confusing varargs with arrays in overloading