Java Varargs
In Java, varargs (short for variable arguments) allow you to pass a variable number of arguments to a method. This feature was introduced in Java 5, enabling developers to create more flexible and readable code.
What are Varargs?
Varargs in Java are denoted using three dots (...
) after the parameter type. The syntax is as follows:
returnType methodName(dataType... variableName) {
// method body
}
Here, dataType...
means you can pass zero or more arguments of that type to the method.
Why use Varargs?
Varargs provide a convenient way to handle situations where you don’t know the exact number of arguments a method will receive. Before varargs were introduced, developers had to rely on overloaded methods or passing arrays, which could make the code cumbersome.
See the below example using Varargs in a Java method:
package org.websparrow;
public class VarargsExample {
// Method that takes variable number of integer arguments
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
// Calling the method with different numbers of arguments
System.out.println("Sum of 1, 2: " + sum(1, 2)); // Output: 3
System.out.println("Sum of 1, 2, 3: " + sum(1, 2, 3)); // Output: 6
System.out.println("Sum of 1, 2, 3, 4, 5: " + sum(1, 2, 3, 4, 5)); // Output: 15
}
}
In the above example, the sum
method accepts a variable number of integers and calculates their sum. You can pass as many arguments as needed, or even none at all. If no arguments are passed, the array would be empty, and the sum would simply be 0
.
Learn more: Find the closest pair from Array to a target value in Java
Key points to remember about Varargs
- Only One Varargs Parameter: A method can have only one varargs parameter. Additionally, it must be the last parameter in the method signature. For example:
public void methodName(String fixedParam, int... varargs) { // valid } // Invalid - Varargs parameter must be the last one public void methodName(int... varargs, String anotherParam) { // Compilation error }
- Varargs are Treated as Arrays: Inside the method, varargs behave like an array. You can access the elements using an index or a loop.
Common use cases of Varargs
- Utility Methods (e.g.,
String.format
): Methods that need to handle an unknown number of inputs, likeString.format
, heavily rely on varargs.String formatted = String.format("Hello, %s! You have %d new messages.", "websparrow", 5);
- Aggregation Functions (e.g., Sum, Min, Max): Methods that perform operations like sum, min, or max over a list of numbers.
public static int min(int... numbers) { if (numbers.length == 0) throw new IllegalArgumentException("No numbers provided"); int minValue = numbers[0]; for (int num : numbers) { if (num < minValue) minValue = num; } return minValue; }
- Custom Logging Methods: Varargs can be used for custom logging utilities where the number of log entries can vary.
public static void log(String level, String... messages) { for (String msg : messages) { System.out.println(level + ": " + msg); } }