Varargs
A varargs parameter accepts zero or more arguments of one type. Write three dots after the type, as in int... scores.
Inside the method, a varargs parameter is an array. That means existing array syntax and enhanced loops work without a new set of rules.
Accept a flexible argument count
public class Main {
static void printNames(String... names) {
for (String name : names) {
System.out.println(name);
}
}
public static void main(String[] args) {
printNames("Maya", "Leo");
printNames("Noah");
}
}
Output:
Maya
Leo
Noah
The same method receives two names in one call and one in another. Inside printNames, both calls look like arrays.
Only the final parameter may be varargs. A call with no varargs supplies an empty array, so the loop would simply print nothing.
Declare values as varargs so total can accept either call shown below.