Sunday, December 19, 2010

Java- Variable length argument


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:

Post a Comment

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...