The challenge

Count how many arguments a method is called with.

Examples

1
2
args_count(1, 2, 3) -> 3
args_count(1, 2, 3, 10) -> 4

The solution in Java code

Some languages refer to this as the spread operator. In Java, this is called a VarArg, which means a Variable Amount of Arguments.

Simply prepend the argument’s name with three dots (...) and then refer to it like an array of elements.

1
2
3
4
5
class Arguments {
  public static int countArgs(Object... args) {
    return args.length;
  }
}

Alternatively, you could also use a stream on it:

1
2
3
4
5
6
7
import java.util.Arrays;

class Arguments {
  public static int countArgs(Object... args) {
    return (int) Arrays.stream(args).count();
  }
}

Or loop through it using a for loop:

1
2
3
4
5
6
7
8
9
class Arguments {
  public static int countArgs(Object... args) {
    int total = 0;
    for (int i = 0; i < args.length; ++i) { 
      total++;
    }
    return total;
  }
}

Test cases to validate our solution

VarArgs can hold multiple variable types, as illustrated in some of our test cases below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.math.BigInteger;

public class SolutionTest {
    @Test
    public void sampleTest() {
        assertEquals(3, Arguments.countArgs(1, 2, 3));
        assertEquals(3, Arguments.countArgs(1, 2, "uhsaf uas"));
        assertEquals(1, Arguments.countArgs(1));
        assertEquals(4, Arguments.countArgs('a', 865, "asfhgajsf", new BigInteger("123456")));
        assertEquals(0, Arguments.countArgs());
    }
}