Showing posts with label Var-Args in Java 5. Show all posts
Showing posts with label Var-Args in Java 5. Show all posts

Sunday, February 8, 2009

Var-Args in Java 5

Java 5 allows methods to take variable number of arguments

Pre Java 5 Example
void doSomething(int i, int j){
Save as Draft

}

This method will be called as follows:
doSomething(10, 20);

Using Java 5, you can declare doSomething method by giving variable arguments as follows:

void doSomething(int... i){
}

And at the time of calling the method, pass any number of arguments as you want.

doSomething(10);
doSomething(10,20);
and so on....

Declaration rules for var-args:
  1. Var-arg Type: When you declare var-args in method, you must specify type of arguments method can receive.
  2. Syntax: Var-args should be declared with type followed by three dots (...) and then name of array that will hold the parameters
  3. Positioning and number of var-args parameters: Var-args must be the last argument in a method signature and you can have only one var-arg in a method.