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.

5 comments:

  1. the ideas are really gud...
    m finding it very helpful in my day to day life....
    thanks dude....
    god bless

    ReplyDelete
  2. Good work, keep it up & keep updating
    Susheel

    ReplyDelete
  3. Nice explanation. Keep adding all other features as well. I found few other features in Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples

    ReplyDelete