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.
As it is written on previous answers, it is
varargs
and declared withellipsis
(...)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
Output
In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:
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).This will do the trick in Java
public void foo(String parameter, Object... arguments);
You have to add three points
...
and thevaragr
parameter must be the last in the method's signature.