Varargs:
Java has included a feature in JDK 5 that simplifies the creation of methods that require a variable number of arguments. This feature is known as varargs, which is an abbreviation for variable-length arguments. A varargs method is one that accepts a variable number of arguments.
Variable-length arguments could be handled in two ways prior to JDK 5. One method employs overloaded methods (one for each), while another places the arguments in an array and then passes this array to the method. Both are potentially error-prone and necessitate more code. The varargs feature is a better, simpler option.
Passing Variable Arguments to a Function in Java using Varargs
Let’s write a function that accepts variable numbers of the same type, in this case int.
We will use the varargs provided by Java to create this type of function. When declaring a function, use elipsis (…) followed by type to indicate that it can accept a variable number of arguments of a given type.
int findProduct(int... numbs);
This function accepts a variable number of integer arguments and internally converts them to an int array before assigning it to the reference name numbs.
Below is the implementation:
int findProduct(int... numbs) { int product = 0; for (int numbers : numbs) { product = product * numbers; } return product; }
Inside the function body, vararg nums will be treated as an array. This array will contain all of the elements passed to it. It simply iterated through the array, calculated the product of all array elements, and returned the value.
Below is the implementation:
import java.io.*; import java.lang.*; import java.util.*; class Codechef { // varargs function which return the product int findProduct(int... numbs) { int product = 1; // traversing the varargs and calculating product for (int numbers : numbs) { product = product * numbers; } // return the product return product; } public static void main(String[] args) throws java.lang.Exception { // Taking a object Codechef sample = new Codechef(); // passing varargs to find product function int product = sample.findProduct(1, 2, 3, 4); System.out.println(product); int[] array1 = { 5, 4, 3, 2, 7}; product = sample.findProduct(array1); System.out.println(product); } }
Output:
24 840
Related Programs:
- how to pass variable arguments in a function in cpp
- python how to unpack list tuple or dictionary to function arguments using and
- how to create and add elements in a hashset in java
- how to reverse a 1d 2d numpy array using np flip and operator in python
- program to reverse a string using a stack data structure in c and python
- java program to display alphabets a to z and a z using loop
- java program to count the number of vowels and consonants in a sentence