How to pass an arbitrary number of the same type arguments to a method using varargs?

Viewed 140

These arguments are specified by three dots after the type. but i don't know what mean of ... in the method

public static void printNumberOfArguments(int... numbers) {
    System.out.println(numbers.length);
}

and also in documentation

public static void method(long.. vararg) { /* do something */ }

this is wrong i don't know why?

2 Answers

It's possible to pass an arbitrary number of the same type of arguments to a method using the special syntax named varargs (variable-length arguments). These arguments are specified by three dots after the type. In the body of the method, you can process this parameter as a regular array of the specified type.

Your method takes an integer vararg parameter and outputs the number of arguments in the standard output using the length property of arrays.

... is a special syntax used here to specify a vararg parameter.

i am trying to provide you both types or passing varargs in methods in java:

incorrect example:

public static void method(double... varargs, int a) { /* do something */ }

The correct version of the method is:

public static void method(int a, double... varargs) { /* do something */ }

A variable-length argument is specified by three periods().

you can invoke the method passing several integer numbers or an array of ints. these some examples will help you to understand this:

printNumberOfArguments(1);
printNumberOfArguments(1, 2);
printNumberOfArguments(1, 2, 3);
printNumberOfArguments(new int[] { }); // no arguments here
printNumberOfArguments(new int[] { 1, 2 });

This code outputs:

1
2
3
0
2
Related