developer
developer

Reputation: 9478

Methods with variable argument list

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".

Upvotes: 6

Views: 9597

Answers (4)

hvgotcodes
hvgotcodes

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

Vincent Ramdhanie
Vincent Ramdhanie

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

kuriouscoder
kuriouscoder

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

anubhava
anubhava

Reputation: 785156

A very simple and practice example of method with variable arguments is String#format method.

Upvotes: 0

Related Questions