Java provides the varargs feature to allow methods to accept a variable number of arguments. This is useful when the exact number of inputs is unknown.
Syntax:
returnType methodName(dataType... variableName) {
// Method body
}
public class VarargsExample {
// Method that accepts variable number of arguments
public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
VarargsExample example = new VarargsExample();
System.out.println("Sum: " + example.sum(1, 2, 3, 4, 5)); // Sum of 5 numbers
System.out.println("Sum: " + example.sum(10, 20)); // Sum of 2 numbers
}
}
Sum: 15
Sum: 30