Saturday, 8 February 2014

Varargs: Methods with variable number of arguments

In java we can create methods that takes variable number of arguments. This feature is called varargs or variable number of arguments. The method which accepts variable number of arguments is called varargs method.
Syntax
    returnType methodName(dataType … parameterName){

    }

"..." tells the compiler that this is a vararg.

Example
class VarargsEx{
 public void printData(int ... a){
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++)
   System.out.print(a[i] + " ");
  System.out.println();
 }

 public static void main(String args[]){
  VarargsEx obj = new VarargsEx();
  obj.printData(1);
  obj.printData(1,2);
  obj.printData(1,2,3);
 }
}

Output
Parameters are 1
1
Parameters are 2
1 2
Parameters are 3
1 2 3

The syntax for the method printData, tells the compiler, that this method can accept zero or more arguments. So all the calls like below are valid.
      obj.printData(1);
    obj.printData(1,2);
    obj.printData(1,2,3);

The variable number of parameters (varargs) must be at last while defining a method with varargs.

There must be only one vararg parameter in method definition.

Some Points to Remember
1. The variable number of parameters (varargs) must be at last while defining a method with varargs.
    Example
class VarargsEx{
 public void printData(int ... a, float f1){ 
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++) 
   System.out.print(a[i] + " ");
  System.out.println();
 } 
} 
           
When you try to compile the above program, compiler will generates error like below

VarargsEx.java:3: error: ')' expected
public void printData(int ... a, float f1){
 ^
VarargsEx.java:3: error: ';' expected
public void printData(int ... a, float f1){
 ^
2 errors
               

valid method definition is
    public void printData(float f1, int ... a)

2. There must be only one vararg parameter in method definition.
      Example
class VarargsEx{
 public void printData(int ... a1, int ... a2){
 }
}
     
When you try to compile the above code, compiler throws error like below             
VarargsEx.java:3: error: ')' expected
public void printData(int ... a1, int ... a2){
 ^

VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
 ^
 
VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
^
3 errors

More about methods                                                 constructore varargs                                                 Home

No comments:

Post a Comment