This post introduces a feature of java that enables you to pass a variable length argument list to any function in java. Once you clearly understand this concept, than you will be able to pass an unspecified number of variables to a function in java using ellipsis(...). Before I start I would like to give you an example where you would find the true application of this concept.
Example :-
Suppose you wish to find average of some numbers, and for this purpose you design a method, which takes all the numbers as arguments and then return the average of these numbers. Now lets have a different thing, suppose if you are not initially specified with the number of arguments that are needed to be passed to the function, then what you will do in that situation? A very obvious answer to this question is that you would pass the whole array and then return the average through that function. But there's a feature in java that enables us to pass a variable length of arguments to a function.
Consider the following source code :-
/********************************************************************************/
public class variable_length_arguments
{
public static void main(String[] args)
{
System.out.println(average(1,2,3,9,1));
}
public static double average(double...nums)
{
double sum=0;
for(double x:nums)
{
sum+=x;
}
return (sum/nums.length);
}
}
/********************************************************************************/
Here, in the above code, we have defined a method, average to compute the average of all the numbers that are passed to it. What actually happens here is a bit tricky, all the arguments that are passed to the function during the function call, are actually stored in a array, nums, using the ellipsis(...). No matter what the number of arguments is, the array in the average method will store all the elements, and now it is very easy for us to calculate the average and return the result. I have here used the concept of enhanced for loop, which I have described in one of my earlier post, and can be reviewed from this link.
No comments:
Post a Comment