var args – The magic in Java

Target Audience: Java Developers
What should you know? Core Java

Writing methods for a class gives completeness for your object. But sometimes it seems to be incomplete when you are not sure about the number of arguments for a method. For example if you are writing a method to find summation of 2 numbers, then the method declaration may be like this:

class MyClass{
  public int sum(int number1, int number2){ // expects 2 ints
     return number1+number2;
   }
}

The above code will always accept 2 arguments. What if you need to write code for summation of N numbers, but not passing the arguments in the form of arrays. The solution is you can use the concept of var args. See the following code:

class MyClass{
   public int sum(int... numbers){ // var args
     int sum=0;
     for (int i=0; i<numbers.length; i++)
       sum += numbers[i];
     return sum;
   }
}

Note the 3 dots after the int data type. The three periods after the parameter’s type indicate that the argument may be passed as an array or as a sequence of arguments. Lets look the method invocation part:


class Demo{
  public static void main(String [] a){
     MyClass m=new MyClass();
     m.sum(100,230);
     m.sum(50, 40, 21, 33);
     m.sum(45);
     m.sum();
  }
}

Will it be compile successfully? Yes, it will. The output is
330
145
45
0

The variable length arguments (var args) in a method declaration accepts zero or any number of arguments of a type. The type may be any primitive data type or pre-defined class or user-defined class. But it has some limits. They are:

  • The var arg must be the last parameter in the method’s signature.
  • You can have only one var arg for a method.

Legal

int sum(int... numbers) { } // expects 0 to many ints
void doSomething(Student... s) { } // 0 to many Students
void abcd(char c, int... x){} // expects a char first, then 0 to many ints

Illegal

int sum(int numbers...) { } // bad syntax
void doSomething(Student... s,String... str) { } // too many var args
void abcd(char... c, int x){} // var arg must be last 0 to many ints

Hope this is useful to you, if not post your comments.

Permanent link to this article: https://blog.openshell.in/2010/12/var-args-the-magic-in-java/

Leave a Reply

Your email address will not be published.