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.

class VarArgsConstDemo {

 public VarArgsConstDemo(int... a) {
  int sum=0;
  for(int i=0;i<a.length;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);
C:\>java VarArgsConstDemo
The sum is 10
The sum is 30
The sum is 60


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.