Varargs Array Part 1 Tutorial

A Variable-Length Argument Array (Varargs) is a special kind of array that can be declared inside of a method or constructor parameter list. Varargs come in very handy when you do not know the exact number of arguments that will be passed to a method. Specifying a varags parameter is easy; first is the data type of the array, then three periods in a row, finally the reference variable name. Just like any other array declared in a parameter list, the reference variable will point to a new array object initialized to the values of the arguments passed to the method.
The structure for a varargs array is like this: methodOrConstructorName( data-type ... referenceVariable )
For example,
void partyList( String ... attendees ) {
      System.out.println("Number of people: " + attendees.length);
      for (int i = 0; i < attendess.length; i++) {
           System.out.print( attendees[i] );
      }
}



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md VarargsOne
C:\Java>cd VarargsOne
C:\Java\VarargsOne>Notepad VarargsOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class VarargsOne {
    public static void main(String args[]) {
        Groupings group1 = new Groupings("Apple", "Orange", "Watermelon");
        Groupings group2 = new Groupings();
        group2.setItems("Tom", "Jane", "Bill", "Mary", "Johnny");
        Groupings group3 = new Groupings(); // empty argument list - interesting

        group1.displayItems();
        group2.displayItems();
        group3.displayItems();
    }
}

class Groupings {
    private String items[];

    Groupings(String ... items) { // Varargs in a constructor - legal, but be careful
        this.items = items;
    }            
    void displayItems() {
        for(String temp : items) {
            System.out.print(temp + "  ");
        }
        System.out.println();
    }

    void setItems(String ... items) { // Varargs in a method
        this.items = items;
    }
}

Now switch back to the command prompt (CMD) and type in javac VarargsOne.java and press Enter.
Now type in java VarargsOne and press Enter.


C:\Java\VarargsOne>javac VarargsOne.java
C:\Java\VarargsOne>java VarargsOne
Apple Orange Watermelon
Tom Jane Bill Mary Johnny


Final thoughts

Stay tuned for part 2 where I will go over the rules for varargs and I will show you how to integrate vargargs into the main method().


Tutorials