How to Pass Dynamic Number of Parameters in Java

Published Aug 27, 2021

Suppose we want a single function to be able to support a dynamic number of parameters.

run(int a, int b);
run(int a, int b, int c);

We can use a useful tool called varargs, or variable arguments, in Java.

It’s denoted by three periods ... in the function declaration.

public void run(int... nums) {};

We can operate on nums as if it were an int[] array.

public void run(int... nums) {
    for (int num : nums)

We can pass in individual arguments like above, or pass in object arrays.

int[] nums = {1, 2, 3};

More Java Articles