Variable Arguments (Varargs) in Java

In JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called varargs and it is short-form for variable-length arguments. A method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded method(one for each) and another put the arguments into an array, and then pass this array to the method. Both of them are potentially error-prone and require more code. The varargs feature offers a simpler, better option.

Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example,

public static void fun(int ... a) 
{
   // method body
} 

This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here a is implicitly declared as an array of type int[]. Below is a code snippet for illustrating the above concept :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate varargs
class Test1
{
    // A method that takes variable number of integer
    // arguments.
    static void fun(int ...a)
    {
        System.out.println("Number of arguments: " + a.length);
  
        // using for each loop to display contents of a
        for (int i: a)
            System.out.print(i + " ");
        System.out.println();
    }
  
    // Driver code
    public static void main(String args[])
    {
        // Calling the varargs method with different number
        // of parameters
        fun(100);         // one parameter
        fun(1, 2, 3, 4);  // four parameters
        fun();            // no parameter
    }
}

chevron_right


Output:

Number of arguments: 1
100 
Number of arguments: 4
1 2 3 4 
Number of arguments: 0