Java Program example to demonstrate variable length of arguments
Program
public class VarArgList
{
void varTest(int ... arg)
{
System.out.println("Number of arguments:\t" + arg.length);
System.out.println("Arguments are:");
int i = 1;
for(int x : arg)
{
System.out.println("arg[" + i + "] : " + x);
i++;
}
System.out.println();
}
public static void main(String[] args)
{
VarArgList argLst = new VarArgList();
argLst.varTest(100);
argLst.varTest(10, 20, 30);
argLst.varTest();
}
}
This Java program demonstrates the concept of variable-length arguments (varargs) using the int ... arg
syntax.
-
Variable-Length Arguments (
int ... arg
):- The method
varTest
accepts a variable number of integer arguments. - The
...
in the method parameter allows the method to take zero or more arguments of the specified type (int
in this case). - Internally, the variable-length arguments are treated as an array.
- The method
-
varTest
Method:- Count of Arguments: The method uses
arg.length
to find the number of arguments passed. - Display Arguments: It iterates over the arguments using an enhanced
for
loop and prints each argument with its index.
- Count of Arguments: The method uses
-
main
Method:- Creates an instance of the
VarArgList
class. - Invokes the
varTest
method with different numbers of arguments:- A single argument:
argLst.varTest(100);
- Multiple arguments:
argLst.varTest(10, 20, 30);
- No arguments:
argLst.varTest();
- A single argument:
- Creates an instance of the
-
Varargs Syntax:
- The
...
syntax allows a method to accept zero or more arguments of a specified type. - Varargs are internally treated as an array.
- The
-
Flexibility:
- The program demonstrates how a single method can handle different numbers of inputs without requiring multiple overloaded methods.
Advantages of Varargs:
- Simplifies method definitions by eliminating the need for method overloading.
- Provides flexibility for accepting varying numbers of arguments.
**Output 1**
```shell
Number of arguments: 1
Arguments are:
arg[1] : 100
Output 2
Number of arguments: 3
Arguments are:
arg[1] : 10
arg[2] : 20
arg[3] : 30
Output 3
Number of arguments: 0
Arguments are: