What are Varargs in Java and How to Use Them
In Java, varargs (variable-length arguments) are a feature that allows a method to accept an arbitrary number of arguments of the same type. The varargs
feature was introduced in Java 5 and is denoted by an ellipsis ...
after the parameter type in the method signature.
Here's an example of a method that uses varargs:
public static int sum(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
In this example, the sum
method takes an arbitrary number of int
arguments, which are stored in an array called numbers
. The method then loops through the array and calculates the sum of all the integers.
Here's how the sum
method can be called:
int result1 = sum(1, 2, 3); // result1 is 6
int result2 = sum(4, 5, 6, 7); // result2 is 22
In both cases, the sum
method is called with multiple int
arguments, but the number of arguments can vary. The varargs
feature allows us to write more flexible and concise code when dealing with methods that take a variable number of arguments.
Note that the varargs
parameter must be the last parameter in the method signature, and a method can only have one varargs
parameter.
Here's another example of a method that uses varargs to concatenate strings:
public static String concatenate(String... strings) {
StringBuilder sb = new StringBuilder();
for (String str : strings) {
sb.append(str);
}
return sb.toString();
}
In this example, the concatenate
method takes an arbitrary number of String
arguments, which are stored in an array called strings
. The method then loops through the array and concatenates all the strings into a single StringBuilder
object, which is then converted to a String
using the toString
method.
Here's how the concatenate
method can be called:
String result1 = concatenate("hello", " ", "world"); // result1 is "hello world"
String result2 = concatenate("foo", "bar", "baz", "qux"); // result2 is "foobarbazqux"
In both cases, the concatenate
method is called with multiple String
arguments, but the number of arguments can vary. The varargs
feature allows us to write more flexible and concise code when dealing with methods that take a variable number of arguments.