21 Dec 2014

Varargs (Variable Arguments) in Java

Variable Argument, termed as varargs are introduced in JDK 1.5 which allows us to write methods which can accept any (zero or multiple) number of arguments. By default, vararg argument is an array. The syntax of vararg method is as follows:
return_data_type  method_name(argument_data_type... argument_name){}
Example:
void sum(int... values){}
Here you can observe that data type of method argument is followed with three dots(...) which is a mark for method argument as variable argument.

Note: If you want to use any other arguments along with vararg then vararg must be the last argument in the method as shown below:
void sum(int value1, int... values){}
If you try to use vararg as other than last argument of a method then you will get compile time error. So, the following syntax is illegal:
void sum(int... values, int value1){}
The following program depicts the usage of vararg of a method to calculate the sum of multiple values.
class A{
     public static void main(String args[]){
          A obj = new A();
          obj.sum();   // 0 arguments
          obj.sum(3);   // 1 argument
          obj.sum(3, 5);   // 2 arguments
          obj.sum(3, 5, 7);   // 3 arguments
     }

     void sum(int... values){
          int sum = 0;
          for(int value:values){
               sum += value;
          }
          System.out.println("SUM:"+sum);
     }
}
If we compile and run the preceding program you will get the following output:
SUM:0
SUM:3
SUM:8
SUM:15

Thus, a method with vararg argument can accept any number of arguments.





Popular Posts

Write to Us
Name
Email
Message