Java Varargs
Java’s varargs feature, introduced in Java 5, is a powerful tool that allows you to pass a variable number of arguments to a method. This feature simplifies method definitions and calls, making your code more concise and easier to maintain. In this article, we’ll explore what varargs are, how to use them, and provide a comprehensive example to illustrate their practical application.
What are Varargs?
Varargs, short for "variable-length arguments," enable you to define a method that accepts zero or more arguments of a specified type. Instead of overloading methods to handle different numbers of parameters, you can use varargs to handle multiple arguments more elegantly.
Syntax of Varargs
The syntax for varargs is straightforward. You use an ellipsis (...) in the method parameter list to indicate that the method can accept a variable number of arguments.
public void methodName(Type... args) {
// Method implementation
}
public static String format(String pattern, Object... arguments);
Points to Remember
- Varargs must be the last parameter: In a method signature, the varargs parameter must be the last parameter. You cannot have other parameters after the varargs parameter.
- Only one varargs parameter: A method can have only one varargs parameter.
- Varargs is treated as an array: Inside the method, the varargs parameter is treated as an array of the specified type.
java.lang.Integer Class Example
public class VarargsExample {
// Method to calculate the sum of multiple integers
public int sum(int... numbers) {
int total = 0;
for (int number : numbers) {
total += number;
}
return total;
}
public static void main(String[] args) {
VarargsExample example = new VarargsExample();
// Calling the sum method with different numbers of arguments
System.out.println("Sum of 1, 2, 3: " + example.sum(1, 2, 3));
System.out.println("Sum of 4, 5, 6, 7, 8: " + example.sum(4, 5, 6, 7, 8));
System.out.println("Sum of no arguments: " + example.sum());
}
}
Output:
Sum of 1, 2, 3: 6
Sum of 4, 5, 6, 7, 8: 30
Sum of no arguments: 0