Saturday, December 29, 2007

VarArgs in Java 5

Introduced in Tiger (Java 1.5.0), variable arguments enables Java methods to accept a variable (0..*) number of arguments thus allowing users greater flexibility in passing calling methods, previously dealt with using arrays.

The last parameter in the list is defined with a "type ... variable_name" syntax (note the ellipsis).

Example:
private static int sum(int ... numbers) {
  int accum = 0;
  for (int i=0; i<numbers.length; i++) {
    accum += numbers[i];
  }
  return accum;
}

No comments: