Arguments and More Arguments: Writing Vararg Methods

Java programmers often need to write methods that accept a parameter containing multiple values. This might take the form of a List or an array, for example.

public int add(int[] list) {
    int sum = 0;
    for (int i=0; i < list.length; i++) {
        sum += list[i];
    }
    return sum;
}

The same code could also have been written as several overloaded methods, each with a signature that takes a different number of int parameters. This sometimes makes the method easier to use, since the calling code does not need to create an array first.

 public int add(int a, int b) { return a + b; } public int add(int ...

Get Wicked Cool Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.