Skip to content

Counting Method VarArgs in Java

The challenge

Count how many arguments a method is called with.


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; } }
Code language: Java (java)

Alternatively, you could also use a stream on it:

import java.util.Arrays; class Arguments { public static int countArgs(Object... args) { return (int); } }
Code language: Java (java)

Or loop through it using a for loop:

class Arguments { public static int countArgs(Object... args) { int total = ; for (int i = ; i < args.length; ++i) { total++; } return total; } }
Code language: Java (java)

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(, Arguments.countArgs()); } }
Code language: Java (java)

See also  (EAI 2)Name or service not known: Could not resolve host name *.80 -- ignoring!
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x