Reputation: 9478
I am preparing for SCJP and I came to know Methods with variable argument list. I have couple questions.
Upvotes: 6
Views: 9597
Reputation: 120198
Its a language feature that allows you to declare a method that will take any number of arguments.
Accordingly, you use it when you don't/can't know how many arguments you will pass to the method. Look at the String.format method. In the method declaration, the final parameter is Object... args
which indicates that format can take any number of arguments.
See also this: http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html
Upvotes: 6
Reputation: 103135
A method with variable argument list implies that you have a method that you can pass variable number of parameters to when you call it. FOr example the String.format() method takes a single String argument and an arbitrary number of other arguments after.
Upvotes: 0
Reputation: 5582
Methods with variable arguments is achieved by triple dot operator ...
. As name suggests, it is used when you have variable argument list. Functionality wise it's similar to pass a single dimensional array of the arguments with one exception that atleast one argument needs to be supplied. Otherwise, it's sometimes preferred over single dimensional array as matter of style. If you look at the caller's code, you would get an idea of how many arguments are passed explicitly. However, if you have more than manageable number of inputs, passing it as array or collection would make more sense.
Upvotes: 2
Reputation: 785156
A very simple and practice example of method with variable arguments is String#format method.
Upvotes: 0