Java - Method with variable-length arguments

What is varargs method?

Varargs method can accept variable-length arguments.

Syntax

To declare a varargs method, add an triple-dot ... after the data type of the method's argument.

int max(int... num) {
    // Code goes here
}

Adding whitespaces before and after ellipsis is optional.

All of the following varargs method declarations are valid.

int max(int... num)  // A space after
int max(int ... num) // A space before and after
int max(int...num)   // No space before and after
int max(int ...
num) // A space before and a newline after

A varargs method can have more than one argument.

The following snippet of code shows that aMethod() accepts three arguments, one of which is a variable-length argument:

int aMethod(String str, double d1, int...num) {
  // Code goes here
}

Rule

Here are the two rules for varargs method.

  • A varargs method can have a maximum of one variable-length argument.
  • The variable-length argument of a varargs method must be the last argument in the argument list.

Related Topic