Working with Varargs parameters

suggest change

Using varargs as a parameter for a method definition, it is possible to pass either an array or a sequence of arguments. If a sequence of arguments are passed, they are converted into an array automatically.

This example shows both an array and a sequence of arguments being passed into the printVarArgArray() method, and how they are treated identically in the code inside the method:

public class VarArgs {
    
    // this method will print the entire contents of the parameter passed in
    
    void printVarArgArray(int... x) {
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + ",");
        }
    }
    
    public static void main(String args[]) {
        VarArgs obj = new VarArgs();
        
        //Using an array:
        int[] testArray = new int[]{10, 20};
        obj.printVarArgArray(testArray); 
       
        System.out.println(" ");
        
        //Using a sequence of arguments
        obj.printVarArgArray(5, 6, 5, 8, 6, 31);
    }
}

Output:

10,20, 
5,6,5,8,6,31

If you define the method like this, it will give compile-time errors.

void method(String... a, int... b , int c){} //Compile time error (multiple varargs )

void method(int... a, String b){} //Compile time error (varargs must be the last argument

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Varargs Variable Arguments:
* Working with Varargs parameters

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
61 Varargs Variable Arguments
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap