Understanding Varargs in Java: 2 Minute Guide For Non-Dummies
By Angsuman Chakraborty, Gaea News NetworkSunday, April 30, 2006
Varargs allows variable number of arguments in methods and constructors. Let’s start with a simple example.
public static void main(String … args) {
for(String arg:args) {
System.out.println(arg);
}
}
Varargs can be thought of as an array with simplifications. A simple use case is: int sum(int… data)
Key Points
- Method with varargs is called only when no other method signature matches the invocation.
- Only one varargs per method can be declared.
- Varargs should be the last argument(set) for a method. So public void varargtest(int i, String … args) is valid but public void varargtest(String … args, int i) is not.
- Zero or more arguments can be passed for varargs unlike an array where at least a null has to be provided.
Now you are all set to play with varargs in Java. Go forth and enjoy!
rohit