Forem

Cover image for Indefinite Arguments
sndp
sndp

Posted on

6 3

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)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay