Wednesday, 3 December 2014

VARIABLE ARGUMENTS - VARARGS -JAVA 5 FEATURE

VARIABLE ARGUMENTS:

It is a feature introduced in Java version 5. It is very handy feature in some situation where you don't know the exact number of arguments for methods.


It is generally known as VARARGS. It is represented by a symbol
ellipsis(...)

Example:
class CountMarks{

//create a static method inorder to access in the main method

static void add(int... params){
          int result=0;
          for(int i:params){
             result=result+i;
          }
          System.out.println("sum of marks: "+result);
      }
    public static void main(String args[]){
        m(10);
        m(10,20,30,23,23,23,23,23);
    }
    }


Output:

sum of numbers: 10
sum of numbers: 175



Rules for varargs:


  1.  There should be only one variable argument in a method.
  2.  The variable argument must be the last argument.
Violating these rules leads to COMPILE TIME ERRORS;

Examples: 

Legal:

void sumUp(int... x) {}
//expects from 0 to many ints as parameters

void sumUp(char chr,int... x) {}
//expects first a char, then 0 to many ints

void sumUp(Salary... sal) {}
//expects 0 to many salary objects

ILLEGAL:

void sumUp(int x...) { }
 //Bad syntax

void sumUp(int... x,char... y) {}
 //too many varargs - rule 1 violated

void sumUp(String... s,char b){} 
// var-arg must be last argument-rule 2 
//violated


Note:  In the above example, We can pass as many numbers as we need, to do the same thing earlier we used to do method overloading. 


No comments:

Post a Comment