Java Variable Arguments
Java allows you to pass a variable number of arguments to a function. We specify several arguments with a variable type followed by an ellipise and a name. The variable number of arguments must come as the last parameter of the function.
Example:
This function takes a variable number of arguments and returns the sum of all the arguments. The key here is that you treat the variable arguments as an array.Code:public static int sum(int... nums) { int nSum = 0; for (int x=0;x<nums.length;x++) { nSum += nums[x]; } return nSum; }
Use this code to test out the function:
There is also a foreach loop that you can use in the function.Code:System.out.println(sum(3,4,2,5)); System.out.println(sum(-1,2)); System.out.println(sum(9,3,5,3,2,3,4,3,2,3,2,1,9,-5));
This code basically does the same thing as above. It assigns each item in the array of parameters to i and then increases the sum by i. They both do the same thing. However, I like the first loop better because it allows me to control where in the array I start and where in the array I stop.Code:public static int sum(int... nums) { int nSum = 0; for (int i: nums) { nSum += i; } return nSum; }
Combining varargs with static arguments
You can use a variable list and static number of arguments. The key here is that the variable arguments list must be declared at the end of the parameter list.
E.g.
In this code the user must pass one integer and then as many integers as they want.Code:public static int product(int n, int... nums) { int product = 1; for (int i=0;i<nums.length;i++) { product *= (nums[i]); } product *= n; return product; }
Example:
In this case, 3 is the integer that must be passed. The rest of the integers are optional.Code:System.out.println(product(3, 4,2,5));
E.g.
Hope this helps! Also it is nice to note that the same functionality exists in C and C++.Code:System.out.println(product(3));
I didn't know Java had this as well. +rep
Me neither. That's great! +rep.
Glad to see you wrote it! Nice work. +rep
+1 of not knowing this also existed in Java. So +rep for teaching us that.
Just now noticed this one
+rep![]()
Last edited by debtboy; 10-10-2009 at 02:26 PM.
Nice work, would rep++ if I knew how.
Click the justice-scale icon next to #1 (permalink) in his post header.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks