Monday 25 July 2022

Constructors with variable number of arguments

In java we can create methods, constructors that takes variable number of arguments. This feature is called varargs or variable number of arguments.

 

Example

public class AirthmeticUtil {

    final int[] args;

    public AirthmeticUtil(int... args) {
        this.args = args;
    }
    .......
    .......
}

 


"..." tells the compiler that this is a vararg, and you can pass zero or more arguments to the AirthmeticUtil constructor.

 

AirthmeticUtil util1 = new AirthmeticUtil();
AirthmeticUtil util2 = new AirthmeticUtil(2);
AirthmeticUtil util3 = new AirthmeticUtil(2, 3);
AirthmeticUtil util4 = new AirthmeticUtil(2, 3, 5);

 

Find the below working application.

 

AirthmeticUtil.java

package com.sample.app.util;

public class AirthmeticUtil {

    final int[] args;

    public AirthmeticUtil(int... args) {

        this.args = args;

    }

    public Long sum() {

        if (this.args == null || this.args.length == 0) {
            return null;
        }

        long sum = 0;

        for (int i : args) {
            sum += i;
        }

        return sum;
    }

    public Long mul() {

        if (this.args == null || this.args.length == 0) {
            return null;
        }

        long result = 1;

        for (int i : args) {
            result *= i;
        }

        return result;
    }

}

 

App.java

package com.sample.app;

import com.sample.app.util.AirthmeticUtil;

public class App {

    public static void main(String[] args) {
        AirthmeticUtil util1 = new AirthmeticUtil();
        AirthmeticUtil util2 = new AirthmeticUtil(2);
        AirthmeticUtil util3 = new AirthmeticUtil(2, 3);
        AirthmeticUtil util4 = new AirthmeticUtil(2, 3, 5);

        System.out.println("Sum of numbers : " + util1.sum());
        System.out.println("Multiplication of numbers : " + util1.mul());

        System.out.println("\nSum of numbers : " + util2.sum());
        System.out.println("Multiplication of numbers : " + util2.mul());

        System.out.println("\nSum of numbers : " + util3.sum());
        System.out.println("Multiplication of numbers : " + util3.mul());

        System.out.println("\nSum of numbers : " + util4.sum());
        System.out.println("Multiplication of numbers : " + util4.mul());

    }
}

Output

Sum of numbers : null
Multiplication of numbers : null

Sum of numbers : 2
Multiplication of numbers : 2

Sum of numbers : 5
Multiplication of numbers : 6

Sum of numbers : 10
Multiplication of numbers : 30



 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment