varargs
In Java, variable-length arguments (varargs) allow a method to accept zero or more arguments of a specified type. This can be very useful when you don't know beforehand how many arguments a method needs to handle.
How to Use Variable-Length Arguments
To declare a varargs parameter in a method, you use an ellipsis (...
) after the type of the arguments. Here’s a basic example:
public class VarArgs {
// Method with varargs to add numbers
void add(int... num) {
int sum = 0;
for (int x : num) {
sum += x;
}
System.out.println(sum);
}
public static void main(String[] args) {
VarArgs obj = new VarArgs();
// Calling the add method with different numbers of arguments
obj.add(10, 20); // Output: 30
obj.add(10, 20, 30); // Output: 60
obj.add(10, 20, 30,40); // Output: 100
}
}
Why Use Varargs?
Convenience: Varargs make it easier to write methods that need to accept a flexible number of arguments. You don’t need to overload the method with different versions for different numbers of parameters.
Readability: Code that calls methods with varargs can be more readable because it doesn't need to construct an array explicitly.
Flexibility: Varargs allow you to handle a varying number of arguments in a single method.
Rules and Limitations
- Only One Varargs Parameter: A method can have only one varargs parameter, and it must be the last parameter in the method’s parameter list. For example:
- Using Varargs: Inside the method, the varargs parameter is treated as an array. You can use it as you would any other array.
Comments
Post a Comment