bhylu.com

Advertisements

Java Accept a Variable Number of Arguments

A varargs parameter lets callers pass zero or more arguments of one element type. Inside the method, that parameter behaves as an array.

Understand the idea

Write the element type followed by ... for the final parameter. Only one varargs parameter is permitted and it must be last. The caller can also supply an existing array, so a method should not unexpectedly mutate it. Decide whether null is accepted and whether an empty argument sequence has an identity result, such as zero for an integer sum.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static int totalSeats(int... groups) {
        int total = 0;
        for (int group : groups) total = Math.addExact(total, group);
        return total;
    }

    public static void main(String[] args) {
        System.out.println(totalSeats(2, 4, 3));
        System.out.println(totalSeats());
    }
}

Expected output

9
0

The first call receives three element values; the second receives an empty sequence. The accumulator’s zero starting value makes the empty result explicit. addExact chooses checked integer addition, but the method still assumes every group count is meaningful. A separate domain rule would reject negative group sizes.

Check the official Java documentation for detailed contracts and supported options.