Varargs – Java 5.0 addition
13 November 2007We 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.
Related Posts:
- Ant (an introduction)
- Using LinkedList (Collection)
- Setting up inheritance - II
- Java performance Issues (II) - Memory
- The Intercepting Filter (I)
- Creating a plug-in project (I)
- PDE - Preparing the workbench
- Java performance Issues (I)
- Creating a Thread (implementing Java Runnable Interface)
- Using PostgreSQL JDBC driver
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