class VarArgs {
public static void main(String[] args) {
SomeClass sc = new SomeClass();
System.out.println("Sum: " +
sc.sum(10, 20, 30, 40));
System.out.println("Sum: " +
sc.sum(10, 20));
}
}
class SomeClass {
int sum(int... values) {
int result = 0;
/*common method using for loop type 1*/
for (int i = 0; i < values.length; i++) {
result += values[i];
}
/* using for loop type 2
for (int value : values) {
result += value;
}*/
return result;
}
}
Note: Variable length arguments are internally treated as arrays.
0 Comments