varargs java example – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 11:09:11 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg varargs java example – Programmerbay https://programmerbay.com 32 32 What do you mean by Varargs in Java? https://programmerbay.com/what-do-you-mean-by-varargs-in-java/ https://programmerbay.com/what-do-you-mean-by-varargs-in-java/#respond Sun, 13 Sep 2020 07:14:33 +0000 https://programmerbay.com/?p=5810 In Java, a method can be created that can take any number of variables as an argument.

A single method can be invoked multiple times in response to various method calls having different numbers of arguments. It avoids unnecessary overloading of the method to perform the same task.

What is Varargs in Java?

The feature that allows a developer to create a method that can accept a variable length of arguments is known as varargs ( Variable Arguments ) and the method is called varargs method.

It was introduced Java 5 onwards.

vararg in java

Before the introduction of Varargs in Java, it required a lot of effort to handle a variable number of arguments ( An argument that is flexible and can accept any number of parameters).

A variable argument can be handled in two ways, first by overloading a method multiple times and secondly by using arrays and put the arguments in arrays and passed to the method.

Syntax:

returnType methodName(dataType ... variableName);

Java program to show the working of varargs ( Variable Arguments )

Program:

public class VargsExample
{
  static void printSum (int ... x)
  {
    int sum = 0;
    for (int num:x)
      {
  sum = sum + num;
      }

    System.out.println ("Total Sum = " + sum);
  }

  public static void main (String[]args)
  {
    printSum (6, 4, 65, 5, 10, 10);
    printSum (50, 10);
  }

}

Output:

Total Sum = 100
Total Sum = 60

Explanation:

In the above varargs example, we declared a vararg that can take any number of integer type variable as an argument and add them together to provide desirable output using for each loop.

]]>
https://programmerbay.com/what-do-you-mean-by-varargs-in-java/feed/ 0