WHAT'S NEW?

The Concept of Var-Args

What is Var-Args?


Var-Args or Variable Length Argument List allows us to write a method that take a varying number of arguments of a specified type.
In simple words same method can take any number or zero arguments of same type if declared using var-args.

How var-args methods look like?


Structure of a var-arg method
If you notice three extra dots are specified after the type of parameter describing it as a var-args method.

When a method argument is of type var-args it is permitted for the method to take one as well as many arguments on the same parameter.
Var-arg method put off the need of making overloaded method when number of parameter is considered.

Let is check that with an example.

public class VarArgsDemo
{
public static void acceptValue(String... s)
{
System.out.println("I m called");
}

public static void main(String[] args)
{
acceptValue();
acceptValue("Tom");
acceptValue("Tom","Alex");
}

}

Output:
Output Screen
When method was called without parameter it was called.
When method was called with one parameter it was called.
When method was passed with two parameter it was called.

This shows that when var-args is used number of parameter can keep varying.


How to access values coming in Var-Args?

The parameter used as var-arg is actually an array. So for accessing the the values coming in it the parameter it has to be accessed like an array.

public static void acceptValue(String... s)
{

for(String x:s)
{
System.out.println(x);


}

Here variable s which was a var-args can be accessed as an array to get the values in it.
Now when the method will be called from above main() output would look something like this.

Accessing Var-Args Parameter


Rules to be followed while working with var-arg.

  1. There can be only one var-args argument in a method.
  2. If the method have more than one parameter, then var-args method should be the last in the order.
Rules for Var-Args





0 comments:

Post a Comment