DEV Community

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay