Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 20, 2021 07:44 am GMT

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)

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);    }}

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)

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);    }}

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);}

Learn more about varargs using the following links.

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


Original Link: https://dev.to/lizardkinglk/indefinite-arguments-4lpe

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To