Thursday, 3 March 2011

Varargs in Java: Variable argument method in Java 5

I think I am late for writing about varargs. The feature of variable argument has been added in Java 5 since its launch. Still I will write something about varargs.
varargs has been implemented in many languages such as C, C++ etc. These functionality enables to write methods/functions which takes variable length of arguments. For example the popular printf() method in C. We can call printf() method with multiple arguments.

1
2
printf("%s", 50);
printf("%d %s %s", 250, "Hello", "World");

 

Syntax

Varargs was added in Java 5 and the syntax includes three dots (also called ellipses). Following is the syntax of vararg method for method called testVar :

1
public void testVar(int count, String... vargs) { }
 
Notice the dots … in above code. That mark the last argument of the method as variable argument. Also the vararg must be the last argument in the method.
Now let us check simple hello world varargs code.
 
Example:
public class HelloWorldVarargs {

public static void main(String args[]) {
test(215, "India", "Delhi");
test(147, "United States", "New York", "California");
}

public static void test(int some, String... args) {
System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
}




In above code, the test() method is taking variable arguments and is being called from main method with number of arguments.


So when should you use varargs?

As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

No comments:

Post a Comment