Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods with variable argument list

Tags:

java

arguments

I am preparing for SCJP and I came to know Methods with variable argument list. I have couple questions.

  1. What is "Methods with variable argument list".
  2. When to use "Methods with variable argument list".
like image 861
developer Avatar asked May 18 '11 17:05

developer


2 Answers

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

like image 83
hvgotcodes Avatar answered Sep 20 '22 12:09

hvgotcodes


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.

like image 39
kuriouscoder Avatar answered Sep 20 '22 12:09

kuriouscoder