Difference between revisions of "Var-Args"
From Suhrid.net Wiki
Jump to navigationJump to searchLine 36: | Line 36: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | * Where it differs from an array is that For a var-args method, the method parameter can be passed "normally", | + | * Where it differs from an array is that For a var-args method, the method parameter can also be passed "normally", in addition to being passed as an array. |
* Example: | * Example: | ||
Line 44: | Line 44: | ||
public static void main(String[] args) { | public static void main(String[] args) { | ||
− | System.out.println(vasum(2, 3, 4)); // | + | System.out.println(vasum(2, 3, 4)); //Variable arguments invocation |
− | System.out.println(arrsum(new int[] {2, 3, 4})); //Array invocation | + | System.out.println(vasum(new int[] {1, 2, 3}); //Array invocation also OK for var-args |
+ | System.out.println(arrsum(new int[] {2, 3, 4})); //Only Array invocation is possible | ||
} | } | ||
Revision as of 22:45, 25 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.
- Example main() can be legally rewritten as :
public static void main(String... args) {
}
- Where it differs from an array is that For a var-args method, the method parameter can also be passed "normally", in addition to being passed as an array.
- Example:
public class VarArgs {
public static void main(String[] args) {
System.out.println(vasum(2, 3, 4)); //Variable arguments invocation
System.out.println(vasum(new int[] {1, 2, 3}); //Array invocation also OK for var-args
System.out.println(arrsum(new int[] {2, 3, 4})); //Only Array invocation is possible
}
public static int vasum(int ... nums) {
int sum = 0;
for(int i : nums) {
sum += i;
}
return sum;
}
public static int arrsum(int[] nums) {
int sum = 0;
for(int i : nums) {
sum += i;
}
return sum;
}
}
- The var-args must be the last parameter in the method's signature. Why ? To resolve situations like this :
sum2(2, 3);
public static void sum2(int a, int... nums) {
}
- Only one var-arg can be declared in the method (even if the var-args are of different types)
public static void sum3( String... strs, int... nums) { //ILLEGAL
}