In Java, a method can be created that can take any number of variables as an argument.
A single method can be invoked multiple times in response to various method calls having different numbers of arguments. It avoids unnecessary overloading of the method to perform the same task.
The feature that allows a developer to create a method that can accept a variable length of arguments is known as varargs ( Variable Arguments ) and the method is called varargs method.
It was introduced Java 5 onwards.
Before the introduction of Varargs in Java, it required a lot of effort to handle a variable number of arguments ( An argument that is flexible and can accept any number of parameters).
A variable argument can be handled in two ways, first by overloading a method multiple times and secondly by using arrays and put the arguments in arrays and passed to the method.
Syntax:
returnType methodName(dataType ... variableName);
public class VargsExample { static void printSum (int ... x) { int sum = 0; for (int num:x) { sum = sum + num; } System.out.println ("Total Sum = " + sum); } public static void main (String[]args) { printSum (6, 4, 65, 5, 10, 10); printSum (50, 10); } }
Output:
Total Sum = 100 Total Sum = 60
Explanation:
In the above varargs example, we declared a vararg that can take any number of integer type variable as an argument and add them together to provide desirable output using for each loop.
This post was last modified on December 27, 2020