How to Use Varargs in Java: Syntax and Examples
In Java, you use
varargs by adding an ellipsis (...) after the parameter type in a method signature, allowing the method to accept zero or more arguments of that type. Inside the method, the varargs parameter behaves like an array, letting you process all passed arguments easily.Syntax
The varargs syntax uses three dots (...) after the type in the method parameter. This means the method can accept any number of arguments of that type, including none. Inside the method, the varargs parameter is treated as an array.
- Type: The data type of the arguments (e.g.,
int,String). - Parameter name: The name you use to access the arguments inside the method.
- Ellipsis (
...): Indicates variable number of arguments.
Only one varargs parameter is allowed per method, and it must be the last parameter.
java
public void methodName(Type... parameterName) { // method body }
Example
This example shows a method that sums any number of integers using varargs. It demonstrates how to call the method with different numbers of arguments.
java
public class VarargsExample { public static int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total; } public static void main(String[] args) { System.out.println(sum()); // No arguments System.out.println(sum(5)); // One argument System.out.println(sum(1, 2, 3, 4)); // Multiple arguments } }
Output
0
5
10
Common Pitfalls
Common mistakes when using varargs include:
- Placing the varargs parameter anywhere but last in the method signature causes a compile error.
- Trying to overload methods with varargs and array parameters can cause ambiguity.
- Assuming varargs can accept different types; all arguments must be of the declared type.
java
public class VarargsMistake { // Wrong: varargs not last // public void wrongMethod(int... nums, String name) { } // Compile error // Correct: public void correctMethod(String name, int... nums) { // method body } }
Quick Reference
Remember these tips when using varargs:
- Use
Type... nameto accept variable arguments. - Varargs parameter must be last in the method signature.
- Inside the method, treat varargs as an array.
- You can call the method with zero or more arguments.
Key Takeaways
Use
Type... name syntax to declare varargs in Java methods.Varargs must be the last parameter in the method signature.
Inside the method, varargs behave like an array you can loop over.
You can call varargs methods with zero or many arguments.
Avoid placing varargs before other parameters to prevent compile errors.