Java

Java – Varargs Explained With Examples

Variable arguments are referred to as “varargs.” You will discover what varargs is in this manual, how to use it in Java, and several examples to help you comprehend this idea fully.

What is varargs?

When you are unsure of how many arguments a method can take, you utilize varaggs. As an example, imagine that you are building a Java application that uses many sum() methods with various numbers of parameters to compute the sum of the input integers.

sum(int a, int b); //to find the sum of two integers
sum(int a, int b, int c); //to find the sum of three integers
sum(int a, int b, int c, int d); //to find the sum of four integers.
...
so on

It’s referred to as method overloading. Since we cannot predict how many numbers the user will supply when calling the method, we have used method overloading to generate a number of versions of this one.

Using the varargs as follows would be another straightforward method of doing the same thing:

sum(int... args);

Just after the data type and before the parameter name, three dots (…) are used. These dots indicate that the args are variable arguments rather than regular arguments (varargs). Now, this same function will help the user even if they provide 100 integers when invoking the sum method.

Let’s examine the whole example to better understand how varargs are used in Java:

Java Program without using varargs

Instead of utilizing varargs in this application, we are using method overloading to handle the various amount of arguments that this method may receive.

public class JavaExample {

  public int sum(int a, int b){
    return a+b;
  }

  public int sum(int a, int b, int c){
    return a+b+c;
  }
  public int sum(int a, int b, int c, int d){
    return a+b+c+d;
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.println(obj.sum(10, 15));
    System.out.println(obj.sum(10, 15, 20));
    System.out.println(obj.sum(10, 15, 20, 25));
  }
}

Output:

25
45
70

The problem with the aforementioned application is that, although functioning flawlessly, it has a limit. The sum of more than four integer values cannot be calculated by the user.

The use of varargs makes this problem simple to resolve:

The same program using varargs

public class JavaExample {

  public int sum(int... args){
    int sum = 0;

    //running a loop to add all numbers.
    for(int num: args){
      sum = sum+num;
    }
    return sum;
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.println(obj.sum(10, 15));
    System.out.println(obj.sum(10, 15, 20));
    System.out.println(obj.sum(10, 15, 20, 25));
    //calculating sum of 7 numbers
    System.out.println(obj.sum(2, 2, 2, 2, 2, 2, 2));
    //calculating sum of 10 numbers
    System.out.println(obj.sum(2, 4, 6, 8, 10, 12, 14, 16, 18, 20));
  }
}

Output:

25
45
70
14
110

As you can see, we didn’t have to worry in this program about how many integers we could send to the sum() function. varargs may accommodate any number of arguments, which explains why.

How varargs works in Java?

Let’s examine the method declaration using the varargs parameter:

public int sum(int... args){
   //statements
}

The three dots… tell the compiler that the argument args is a variable and not a typical argument. The preceding code sample shows how the compiler internally produces an array called args (args[]), whose data type matches that of args, which is an int.

Thus, the compiler internally declared an array args[] with the data type int for the aforementioned procedure sum().

The array’s size was then determined by the compiler using the parameters. If you use the syntax sum(10, 20, 30), the compiler will adjust the size of the arguments to 3.

When to use varargs in Java

Not all situations call for the varargs. In the following circumstances, you ought to use varargs:

  • If you’re unsure of how many arguments a user may send when calling a method, number one.
  • If you anticipate that the method parameter will function as an array.

The predefined function String.format() from the String class is a well-known illustration of this. Any number of parameters may be used with this procedure.

String.format("My number: %d", num);
String.format("My number: %d and my string: %s", num, str);

Method overloading for the methods with Varargs parameter

As seen below, we may overload a method with the varargs argument. Here, a method sum has been overloaded (). This method’s first variant supports variable int inputs and outputs their total. The concatenated text is printed by the second iteration of the sum() function, which also takes variable string parameters.

class JavaExample {

  public void sum(int... num){
    int sum = 0;
    for (int i: num) {
      sum += i;
    }
    System.out.println( sum);
  }

  public void sum(String... str){
    String str2 = "";
    for (String s: str) {
      str2 = str2.concat(s);
    }
    System.out.println(str2);
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.print("Output of int varargs method: ");
    obj.sum(10, 20, 39);
    System.out.print("Output of String varargs method: ");
    obj.sum("Beginners", "Book", ".com");
  }
}

Output:
Java - Varargs Explained With Examples

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button