Skip to main content

Posts

Showing posts from August, 2019

Using varargs(Variable -length argument) in Java

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, 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", &