Wednesday, February 29, 2012

A student asked me if there's a simple way of making a method that takes a variable number of arguments. In Java, using the ... notation, you can do just that! Let's say, for example, you want to create a method that will add up any number of integer numbers. Using the code below, you can do just that. So simple, so easy, so elegant.

public class AddUpMany { 
  public int addThemAll(int... numbers) { 
    int total = 0; 
    for (int temp : numbers) { 
      total += temp; 
    return total; 

  public static void main(String args[]) { 
    AddUpMany instance = new AddUpMany(); 
    System.out.println("Adding up 5 and 6 gives you " + instance.addThemAll(5,6));      
    System.out.println("Adding up 5,5 and 2 gives you " + instance.addThemAll(5,5,2));
    System.out.println("Adding up 1,2 and 3 gives you " + instance.addThemAll(1,2,3)); 

No comments:

Post a Comment