I am preparing for SCJP and I came to know Methods with variable argument list. I have couple questions.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With