![]() |
VOOZH | about |
Variable Arguments (Varargs) in Java allow methods to accept a variable number of parameters using a simplified syntax. Introduced in Java 5, it improves flexibility and reduces the need for multiple method overloads. Internally, varargs are handled as arrays, making them easy to process within methods.
geek1 geek2 geek1 geek2 geek3
Explanation: In the above example, the String... names allows the method to accept a variable number of String arguments. Inside the method, the for-each loop iterates over the names array and prints each name. The method is called twice in main(), with two and three arguments respectively.
Syntax:
Internally, the Varargs method is implemented by using the single dimensions arrays concept. Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…).
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].
Example: Demonstrating the working of varargs with integer argument
Number of arguments: 1 100 Number of arguments: 4 1 2 3 4 Number of arguments: 0
Explanation: In the above example, the fun(int... a) method accepts a variable number of integers. The length of the arguments is accessed using a.length. A for-each loop is used to iterate over the arguments and print each value.
Note: A method can have variable length parameters with other parameters too, but one should ensure that there exists only one varargs parameter that should be written last in the parameter list of the method declaration. For example:
int nums(int a, float b, double … c)
In this case, the first two arguments are matched with the first two parameters, and the remaining arguments belong to c.
Example: Varargs with Other Arguments
String: GeeksforGeeks Number of arguments is: 2 100 200 String: CSPortal Number of arguments is: 5 1 2 3 4 5 String: forGeeks Number of arguments is: 0
void method(String... gfg, int... q)
{
// Compile time error as there
// are two varargs
}
Note: Only one Varargs parameter is allowed per method.
void method(int... gfg, String q)
{
// Compile time error as vararg
// appear before normal argument
}