Varargs – Java 5.0 addition

13 November 2007

We all are familiar with methods in lava. Methods are an important artifact of programming. Method contains signature and body. Method body is enclosed in braces. Method signature comprises of its name, access modifier, return type and list of parameters.

public String methodName(String arg0,int arg1)
{return string;
}

Methods can also be static which means they can be accessed without using any object.

Number of input parameters can be varied in methods depending on needs. But while coding/developing application, you have to specify the number of input parameters a method will take. Of course you can use Array, ArrayList or Vectors as well.

Java 5.0 introduced … notation in the method’s input parameter area to make methods flexible. If you have a method whose count of input parameters is not fixed and you want to keep it flexible, then … notation introduced in Java 5.0 is the right choice.

Reiew the function below:

public static void myMethod(Object ... args){
System.out.println("myFunction called.");
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}

Now,w e will call this method with 2 and 3 parameters and lets see the output:

myMethod("Australia","Austria");
myMethod("Sweden","Germany","France");

Output:

myMethod called.
Australia
Austria
myMethod called.
Sweden
Germany
France

Hence it is clear that method named myMethod is flexible and can take any number of parameters. It uses … notation to take an args array of type Object. This newly introduced feature is very useful in day to day programming task.

Happy programming.

del.icio.us:Varargs – Java 5.0 addition  digg:Varargs – Java 5.0 addition  spurl:Varargs – Java 5.0 addition  wists:Varargs – Java 5.0 addition  simpy:Varargs – Java 5.0 addition  newsvine:Varargs – Java 5.0 addition  blinklist:Varargs – Java 5.0 addition  furl:Varargs – Java 5.0 addition  reddit:Varargs – Java 5.0 addition  fark:Varargs – Java 5.0 addition  blogmarks:Varargs – Java 5.0 addition  Y!:Varargs – Java 5.0 addition  smarking:Varargs – Java 5.0 addition  magnolia:Varargs – Java 5.0 addition  segnalo:Varargs – Java 5.0 addition  gifttagging:Varargs – Java 5.0 addition

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Varargs – Java 5.0 addition

Leave a Reply