Home » Java Basics » 04 - Class and Object Concepts
4

Varargs

A variable number of input parameters

A Java concept called varargs allows functions to take a variable number of input parameters. For example, in our Fruit class, the number of colors associated with a fruit varies. An apple may be green, red, or yellow; while an orange is only orange. We could model a varargs constructor for the Fruits class as follows:

        public Fruit(String name,String image,int calories,String... color) {
this.name = name;
this.color.addAll(color);
if (color.length <= 10 )  {
System.arraycopy(color,0,this.color,0,color.length);
}
else   {
System.arraycopy(color,0,this.color,0,10);
}
this.image = image;
this.calories = calories ;
}

Notice that the 'String... color' input parameter may contain a variable amount of Strings. The 'color' argument is treated exactly like an array in the constructor. In fact, the calling function could pass either as an array of Strings or a sequence of strings separated by commas to the constructor. The following two instance creation statements for the above varargs method are equivalent:

Fruit apple = new Fruit("Apple","apple.PNG",70,red, yellow, green)

is the same as ..

String[] appleColors = {"red","yellow","green");
Fruit apple = new Fruit("Apple","apple.PNG",70,appleColors)

Varargs are used very extensively by 'System.out.printf' type methods. A printf method takes in as many arguments as there are variables denoted by a leading '%' in the initial string and an additional argument for the initial formatted string literal.

printf with variable arguments

System.out.printf("Numbers: %d %d %d $%.2f %n",i,j,k,money)  //5 Arguments
System.out.printf("Number and Character: %d  %c %n",i,myChar) //3 Arguments