Java variable number or arguments for a method Java variable number or arguments for a method java java

Java variable number or arguments for a method


That's correct. You can find more about it in the Oracle guide on varargs.

Here's an example:

void foo(String... args) {    for (String arg : args) {        System.out.println(arg);    }}

which can be called as

foo("foo"); // Single arg.foo("foo", "bar"); // Multiple args.foo("foo", "bar", "lol"); // Don't matter how many!foo(new String[] { "foo", "bar" }); // Arrays are also accepted.foo(); // And even no args.


Yes, it's possible:

public void myMethod(int... numbers) { /* your code */ }


Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {     int currentLargest = numbers[0];     for (int number : numbers) {        if (number > currentLargest) {            currentLargest = number;        }     }     return currentLargest;}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012