Java varargs provides the facility to a method to accept variable number of arguments. Varargs refers to variable-length arguments. A variable-length argument is specified by three dots (…) also known as ellipsis. Before varargs, variable-length arguments handled either by using method overloading or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. The varargs feature offers an easy and better option.
Syntax
return_type method_name(data_type... variableName){}
Note:
- There can be only one variable argument in a method.
- Variable argument (varargs) must be the last argument.
- Vararg methods can also be overloaded but it may lead to ambiguity.
How java varargs work?
The three dots (…) syntax tells the compiler that varargs has been used and these arguments should be stored in the array. When we call a method with variable arguments, java compiler matches the arguments from left to right and creates an array of the remaining arguments when reaches to the last varargs parameter, and pass it to the method. The varargs parameter represents an array of the specified type.
Java varargs example
package com.w3spoint; public class JavaVarargsTest { static void display(int num, String... values){ System.out.println("In display method "); System.out.println("Number value: "+num); for(String value:values){ System.out.println(value); } } public static void main(String args[]){ //zero argument as Varargs display(100); //one argument as Varargs display(150, "Hello w3spoint"); //three arguments as Varargs display(250, "jai","mahesh","vivek"); } } |
Output
In display method Number value: 100 In display method Number value: 150 Hello w3spoint In display method Number value: 250 jai mahesh vivek |