Variadic Function
In Java, variadic functions allow you to pass a variable number of arguments to a method. Unlike regular methods, which have a fixed number of parameters, variadic functions can accept a varying number of arguments. This flexibility is achieved using an ellipsis (...
) in the method parameter list. Here's how variadic functions work in Java:
Syntax for Variadic Function:
return_type methodName(data_type... variableName) {
// Method implementation
}
return_type
: Specifies the data type the method returns.methodName
: Specifies the name of the variadic function.data_type... variableName
: Indicates a variable number of parameters of the specified data type.Inside the method, you can treat
variableName
as an array of the specified data type.
Example of Variadic Function:
public class VariadicFunctionExample {
// Variadic function to calculate the sum of integers
public static int calculateSum(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
int sum1 = calculateSum(1, 2, 3, 4, 5);
int sum2 = calculateSum(10, 20, 30);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
}
Explanation:
public static int calculateSum(int... numbers) { ... }
: This line defines a variadic function namedcalculateSum
. It accepts a variable number of integers (numbers
) as arguments.for (int num : numbers) { sum += num; }
: In the method body, the function iterates over thenumbers
array (which is treated as an array due to the variadic parameter) and calculates the sum of all integers passed to the function.int sum1 = calculateSum(1, 2, 3, 4, 5);
: This line calls thecalculateSum
function with five integers as arguments and assigns the returned sum to the variablesum1
.int sum2 = calculateSum(10, 20, 30);
: This line calls thecalculateSum
function with three integers as arguments and assigns the returned sum to the variablesum2
.System.out.println("Sum 1: " + sum1);
: Prints the sum of the first set of integers.System.out.println("Sum 2: " + sum2);
: Prints the sum of the second set of integers.
When you run this Java program, it will output:
Sum 1: 15
Sum 2: 60
This output demonstrates the usage of variadic functions to handle different numbers of arguments, providing flexibility in method calls.
Last updated