Friday, May 14, 2010

Varargs methods

Varargs methods have been introduced in Java 5, but they currently don’t have a wide diffusion and most part of the Java developers are not aware of their existence.

The vararg notation allows methods to accept a variable number of arguments and packs them into an array. This notation is not as convenient as you might like, because the arrays it creates suffer from the same issues involving reification as other arrays.

A Varargs methods is a standard Java method that can be invoked using a different number of objects as parameters. Example:
 // Method declaration  
 public void print(String... strs) {  
      for (int i = 0; i < strs.length; i++) {  
           System.out.println(strs[i]);  
      }  
 }  
 // Method call  
 print(null, "Hello", "World", "!");  
The syntax "String…" stands for "any number of objects of type string". You can manage this “strange” object as a normal array inside the method body. From the method writer point of view, a Varargs method is just a method with an array as its last argument. The real difference between this method and a standard one becomes evident when it is invoked. Note that the first argument is ignored in the declaration of the print method and if you desire you can write a method using just a Varargs parameter and nothing else.
The compiler translates
 return arithmetic.add(x, x, x);  
to
 return arithmetic.add(x, new Object[] {x, x});  
when the type is given in the method call. It is, as if it was doing the translation before making the decision of the T type.
 int testMethod (int x, int y, int z, int ... n) {}  
A method can accept "normal" parameters along with variable length parameter lists. To do this you must ensure that the variable length parameter list is declared last. Also, a method can't declare more than one varargs parameter.
SYNTAX:
 methodName (type t1, type t2, type t ... arguments) {}  
NOTE: Statements/Snippets taken from multiple posts purely for my understanding as well as jotting different experiences at a single place.

1 comment:

Ameya Aloni said...

Few people recently asked me, "Can I overload a Varargs method?". Well answer is "Yes, off-course!". Here's how you can do it:

class TestVarargs {
// integer varargs parameter
static void testMethod (int ... testArray) {
// some code goes here...
}
// overloaded: boolean varargs parameter
static void testMethod (boolean ... testArray) {
// some code goes here...
}
// overloaded: 'normal' String and integer varargs parameter
static void testMethod (String msg, int ... testArray) {
// some code goes here...
}
public static void main (String[] args) {
testMethod (5); // 1 arg
testMethod ("Integers ", 0, 7); // 3 args
testMethod (false, true, false); // 3 args
}
}