Java 5.0 supports invoking methods with a variable number of arguments (Var-args). The variable arguments are received in the method parameter as an array object. There can be only one variable argument parameter in a method and it must be the last one in the order of parameters. The variable-argument parameter is declared in the method as follows:
[type of parameter][ellipsis (three dots)][white-space][name of array variable]
For example, the following declares a String-type var-arg, and the arguments are stuffed in a String array:
String... strArray
[type of parameter][ellipsis (three dots)][white-space][name of array variable]
For example, the following declares a String-type var-arg, and the arguments are stuffed in a String array:
String... strArray
package info.icontraining.core;
public class VarargExample {
public static void main(String[] args) {
varargMethod(true, "A", "B", "C");
varargMethod(false,"E", "F");
varargMethod(true, "G", "H", "I", "J");
}
public static void varargMethod(boolean b, String... names) {
System.out.println("Number of var-arg values: " + names.length);
for (String s: names) {
System.out.print(s + " ");
}
System.out.println();
}
}
Good example. varargs is a nice feature and suits great on a particular type of method like sum(), avg() etc. By the way here is few more points worth noting on varargs method in Java. you may like.
ReplyDelete