Counting Method VarArgs in Java


The challenge

Count how many arguments a method is called with.

Examples

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.

class Arguments {
  public static int countArgs(Object... args) {
    return args.length;
  }
}

Alternatively, you could also use a stream on it:

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:

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.

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());
    }
}