Difference between revisions of "Var-Args"
From Suhrid.net Wiki
Jump to navigationJump to search (Created page with "* Var-args are used to defined methods with variable argument lists. * Syntax <type>... <varargname>") |
|||
| Line 1: | Line 1: | ||
* Var-args are used to defined methods with variable argument lists. | * Var-args are used to defined methods with variable argument lists. | ||
* Syntax <type>... <varargname> | * Syntax <type>... <varargname> | ||
| + | * Example: | ||
| + | |||
| + | <syntaxhighlight lang="java5"> | ||
| + | |||
| + | public class VarArgs { | ||
| + | |||
| + | public static void main(String[] args) { | ||
| + | System.out.println(sum(2, 3, 4)); | ||
| + | } | ||
| + | |||
| + | public static int sum(int... nums) { | ||
| + | int sum = 0; | ||
| + | for(int i : nums) { | ||
| + | sum += i; | ||
| + | } | ||
| + | return sum; | ||
| + | } | ||
| + | |||
| + | } | ||
| + | |||
| + | |||
| + | * The ellipsis can be located anywhere e.g. (int... nums) or (int ...nums) or (int ... nums) is fine. | ||
| + | * Essentially the method argument is treated as an array within the method. so nums is an int[] array. | ||
| + | |||
| + | |||
| + | </syntaxhighlight> | ||
Revision as of 03:44, 24 August 2011
- Var-args are used to defined methods with variable argument lists.
- Syntax <type>... <varargname>
- Example:
public class VarArgs {
public static void main(String[] args) {
System.out.println(sum(2, 3, 4));
}
public static int sum(int... nums) {
int sum = 0;
for(int i : nums) {
sum += i;
}
return sum;
}
}
* The ellipsis can be located anywhere e.g. (int... nums) or (int ...nums) or (int ... nums) is fine.
* Essentially the method argument is treated as an array within the method. so nums is an int[] array.