Sometimes you might want to write a method that takes a variable number of arguments. In Java, there is a feature called variable-length arguments, or varargs for short, which allows you to do this. Prior to JDK 5, variable-length arguments could be handled in two ways,
syntax for varargs
- using overloading
- using array argument.
syntax for varargs
public static String format(String pattern, Object... arguments);
- The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
- Varargs can be used only in the final argument position
- There can be only one variable argument in a method.
- Vararg Methods can also be overloaded but overloading may lead to ambiguity.
Example:
public class Varargs {
public static void main(String[] args) {
printItems(1,2, "mango", "apple", "orange");
printItems(2,1, "book", "pen", "pencil", "cheese");
}
public static void printItems(int a, int b, String... items) {
System.out.println(" --------- Shopping items ----------\n");
for(int i = 0; i < items.length; i++) {
System.out.println(items[i]);
}
}
}
Output :--------- Shopping items ---------- mango apple orange --------- Shopping items ---------- book pen pencil cheese
Comments
Post a Comment