In this article we will look at what is variable length arguments or varargs is and how to use variable length arguments in methods to solve the complexity of a Java program.
There might be some situations while creating methods, where the programmer might not know how many arguments are needed in the method definition or how many arguments are going to be passed at run-time by the user. Prior to Java 5, there were a couple of workarounds for this problem but was often complex or error prone.
With Java 5, a new feature called varargs was introduced which allows programmers to specify variable length arguments in the method definition. A method with variable length arguments is specified as shown below:
return-type method-name(type … variable-name) { }
In the above method declaration, ellipses (…) represents variable length arguments. We can also specify normal variables along with variable length arguments in the method definition. There are two rules that should be followed while working with variable length arguments. They are as follows:
- When normal variables (arguments) are specified along with variable length arguments, the variable length argument should be the last in the list of arguments.
- One cannot specify more than one variable length argument in a method definition.
Below example Java program demonstrates the use of variable length arguments (varargs):
class VarArgsDemo
{
public static void main(String[] args)
{
VarArgsDemo v = new VarArgsDemo();
v.sum(1);
v.sum(1, 2);
v.sum(1, 2, 3);
}
public void sum(int ... var)
{
int s = 0;
for(int x : var)
s += x;
System.out.println("Sum is: " + s);
}
}
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply