Tuesday, August 27, 2013

varargs - variable arguments


package NewFeatures;

/**
* @author sanjeeva
* varargs - Variable Arguments
* varargs comes with Java 5
* varargs allows to method to accept zero or more arguments.
* varargs is a better approach when we don't know how many arguments will have to pass
*
* syntax : (data_type... variableName)
*
* Rules -
* 1. can be only one variable argument in the method
* 2. variable argument must be the last argument
*/
public class VarArgsExample {

   /**
   * @param args
   */
   public static void main(String[] args) {
       VarArgsExample example = new VarArgsExample();
       example.doExecute();
   }

   private void doExecute(){
        display(); //zero argument
        display("Sanjeeva","Pathirana"); //two arguments
        display(100, "Sri Lanka","India","Pakistan");
   }

   private void display(String... values){
        System.out.println("call display() -->");
        for(String arg: values){
            System.out.println(arg);
        }
   }
 
   private void display(int id, String... values){
         System.out.println("call display() -->");
         for(String arg: values){
            System.out.println(arg);
         }
   }

}