116

In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.

I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
Omar Kooheji
  • 54,530
  • 68
  • 182
  • 238

3 Answers3

206

In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:

public void foo(Object... bar) {
    for (Object baz : bar) {
        System.out.println(baz.toString());
    }
}

The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[] in this case).

David Grant
  • 13,929
  • 3
  • 57
  • 63
  • 3
    Thanks I bizzarrly found this out myself while I was looking up something else, and was coming here to answer the question myself. – Omar Kooheji Feb 06 '09 at 10:17
  • Note that the ellipse is three periods (correctly typed in the answer as ...) and not an actually typed ellipse … – MVinca May 03 '23 at 16:37
11

This will do the trick in Java

public void foo(String parameter, Object... arguments);

You have to add three points ... and the varagr parameter must be the last in the method's signature.

user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
Stefano Driussi
  • 2,241
  • 1
  • 14
  • 19
3

As it is written on previous answers, it is varargs and declared with ellipsis (...)

Moreover, you can either pass the value types and/or reference types or both mixed (google Autoboxing). Additionally you can use the method parameter as an array as shown with the printArgsAlternate method down below.

Demo Code

public class VarargsDemo {

    public static void main(String[] args) {
        printArgs(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
        printArgsAlternate(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
    }

    private static void printArgs(Object... arguments) {
        System.out.print("Arguments: ");
        for(Object o : arguments)
            System.out.print(o + " ");

        System.out.println();
    }

    private static void printArgsAlternate(Object... arguments) {
        System.out.print("Arguments: ");

        for(int i = 0; i < arguments.length; i++)
            System.out.print(arguments[i] + " ");

        System.out.println();
    }

}

Output

Arguments: 3 true Hello! true 25.3 a X 
Arguments: 3 true Hello! true 25.3 a X 
Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106