Friday, 25 November 2016

Demonstrate use of varargs (Variable length arguments) in constructor

The varargs is variable length arguments that allows the method to accept zero or multiple arguments. Before varargs either we use overloaded method or take an array as the method parameter. If we don't know how many argument we will have to pass in the method, varargs is the better approach. The main advantage of is that we don't have to provide overloaded methods as a result so less code. The syntax for varargs is given below:
access_specifier   class-name( data_type...   variable-name){
 .
 .
}  

Note that you have to insert three dots(...) after data type.

In program we have provided variable length arguments in constructor. Then at the time of constructor call we give variable arguments.


PROGRAM
class VarArgsConstDemo {

 public VarArgsConstDemo(int... a) {
  
  int sum=0;
  for(int i=0;i<a.length;i++)
  {
   sum+=a[i];
  }
  System.out.println("The sum is "+sum);
 }
 
 public static void main(String[] args) {
  
  VarArgsConstDemo v1 = new VarArgsConstDemo(10);
  VarArgsConstDemo v2 = new VarArgsConstDemo(10,20);
  VarArgsConstDemo v3 = new VarArgsConstDemo(10,20,30);
 }
}
OUTPUT
C:\>javac VarArgsConstDemo.java
C:\>java VarArgsConstDemo
The sum is 10
The sum is 30
The sum is 60

No comments:

Post a Comment