DEV Community

Cover image for Indefinite Arguments
sndp
sndp

Posted on

Indefinite Arguments

When your program needs indefinite number of arguments, and let's say,

i. You are not allowed to pass a collection or an array.
ii. You are not allowed to overload methods.

Using varargs is the best option to use in this case.

Before varargs was introduced in Java 5, the problem was solved by allowing to use any of the mentioned two ways above.

A varargs method can pass indefinite number of arguments with the following method definition. (In here the data type is String and args is the name of the argument)

void someMethod (String... args)
Enter fullscreen mode Exit fullscreen mode

Below is an use-case that used varargs to solve a problem which involved printing the sum of numbers.
Not allowing to use overloading or passing a collection or an array.
So we use varargs.

class Add {
    public void add(int... nums) {
        int sum = 0;
        String label = " ";
        for (Integer n: nums) {
            label += n + " ";
            sum += n;
        }
        label = label.trim().replace(" ", "+");
        label += String.format("=%d", sum);
        System.out.println(label);
    }
}
Enter fullscreen mode Exit fullscreen mode

In the context of C# language we change the syntax a little bit.
We add the keyword 'params' to define it is a varargs method.

It looks like this.

void add(params int[] nums)
Enter fullscreen mode Exit fullscreen mode

And the same code for above problem in C# language is as below.

class Add {
    public void add(params int[] nums) {
        int sum = 0;
        String label = " ";
        foreach (int n in nums) {
            label += n + " ";
            sum += n;
        }
        label = label.Trim().Replace(" ", "+");
        label += String.Format("={0}", sum);
        Console.WriteLine(label);
    }
}
Enter fullscreen mode Exit fullscreen mode

Call to your method like below in your main method.
And again -> use any number of arguments.

public static void main(String[] args) {
    new Add().add(1, 2, 3);
    new Add().add(1, 2, 3, 4, 5);
}
Enter fullscreen mode Exit fullscreen mode

Learn more about varargs using the following links.

https://www.baeldung.com/java-varargs

Top comments (0)