Java Programming Handbook

    Variable Arguments (varargs) in Java

    In Java, variable arguments (also called varargs) allow us to pass a variable number of arguments to a method. This feature simplifies method definitions by eliminating the need to define multiple overloaded methods for different argument counts.

    Why Use Variable Arguments?#

    • Allows a method to accept any number of arguments
    • Eliminates the need for method overloading in some cases
    • Increases code reusability and reduces redundancy

    Syntax of varargs#

    We use an ellipsis (...) after the data type to define a varargs method:

    returnType methodName(dataType... variableName) { }

    Example:

    void displayNumbers(int... numbers) { // Method body }

    Example: Using Variable Arguments#

    class VarargsExample { // Method with variable arguments static void printNumbers(int... numbers) { System.out.println("Number of arguments: " + numbers.length); // Loop through numbers and print each for (int num : numbers) { System.out.print(num + " "); } System.out.println(); } public static void main(String[] args) { // Calling method with different number of arguments printNumbers(10, 20, 30); printNumbers(5, 15); printNumbers(100); } }

    Output:#

    Number of arguments: 3 10 20 30 Number of arguments: 2 5 15 Number of arguments: 1 100

    Explanation:

    • The method printNumbers(int... numbers) can accept any number of integers.
    • The numbers.length property helps in knowing the number of arguments passed.

    Varargs with Other Parameters#

    A varargs parameter must always be the last parameter in the method signature.

    Example: Valid Varargs Usage#

    class Example { static void showDetails(String name, int... marks) { System.out.println("Student: " + name); System.out.print("Marks: "); for (int mark : marks) { System.out.print(mark + " "); } System.out.println(); } public static void main(String[] args) { showDetails("Alice", 85, 90, 95); showDetails("Bob", 80, 88); } }

    Output:#

    Student: Alice Marks: 85 90 95 Student: Bob Marks: 80 88

    Explanation:

    • The name parameter is required, and varargs marks can take multiple values.
    • Order matters: Regular parameters must come before varargs.

    Limitations of Varargs#

    Cannot have multiple varargs in a method

    void example(int... a, double... b) { } // ❌ Compilation error

    Must be the last parameter in the method

    Conclusion#

    In this blog, we learned how to pass Varargs to the method.

    • Varargs allows a method to take a variable number of arguments.
    • It eliminates overloading, making code more concise.
    • It must be the last parameter in the method signature.

    Last updated on Apr 09, 2025