Var-args (variable arguments) in Java allow a method to accept zero or more arguments of the same type. They simplify method calls by removing the need to explicitly create arrays.
... (ellipsis) syntaxVar-args make methods flexible when the number of inputs is unknown. They improve readability and reduce overloaded methods.
// Method using var-args to accept multiple integers
static void printNumbers(int... numbers) {
// Loop through all received values
for (int n : numbers) {
System.out.println(n);
}
}
// Demonstrating var-args usage in main method
public class VarArgsDemo {
public static void main(String[] args) {
// Calling method with different number of arguments
printSum(10);
printSum(10, 20, 30);
printSum();
}
// Var-args method to calculate sum
static void printSum(int... values) {
int sum = 0;
for (int v : values) {
sum += v;
}
System.out.println("Sum = " + sum);
}
}
Sum = 10
Sum = 60
Sum = 0
The method printSum works with one value, multiple values, or even no values. Java automatically converts the arguments into an integer array.