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:
Example:
Example: Using Variable Arguments#
Output:#
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#
Output:#
Explanation:
- The
name
parameter is required, and varargsmarks
can take multiple values. - Order matters: Regular parameters must come before varargs.
Limitations of Varargs#
❌ Cannot have multiple varargs in a method
❌ 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.