View RSS Feed

My Java Tips

Varargs – Java 5.0 addition

Rate this Entry
by , 11-09-2011 at 07:08 PM (1244 Views)
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.

Java Code:
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.

Review the function below:

Java Code:
public static void myMethod(Object ... args){
System.out.println("myFunction called.");
for(int i=0;i
Now,we will call this method with 2 and 3 parameters and lets see the output:



myMethod called.
myMethod called.

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.

Submit "Varargs – Java 5.0 addition" to Facebook Submit "Varargs – Java 5.0 addition" to Digg Submit "Varargs – Java 5.0 addition" to Submit "Varargs – Java 5.0 addition" to StumbleUpon Submit "Varargs – Java 5.0 addition" to Google

Tags: None Add / Edit Tags
Java SE