Java - Varargs in Java
Varargs, short for Variable Arguments, is a feature in Java that allows a method to accept zero or more arguments of the same data type. It is useful when you do not know in advance how many values will be passed to a method.
Varargs were introduced in Java 5 and provide a convenient way to pass a variable number of arguments without manually creating an array.
1. Why Are Varargs Needed?
Normally, a method has a fixed number of parameters.
public static int add(int a, int b) {
return a + b;
}
This method can accept only two integers.
If we want to add three or four numbers, we would need to create different methods:
public static int add(int a, int b, int c) {
return a + b + c;
}
public static int add(int a, int b, int c, int d) {
return a + b + c + d;
}
Creating multiple methods for different numbers of arguments is inconvenient.
Varargs solve this problem by allowing one method to accept any number of arguments.
public static int add(int... numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
Now the same method can be called with different numbers of arguments:
System.out.println(add(10, 20));
System.out.println(add(10, 20, 30));
System.out.println(add(10, 20, 30, 40, 50));
The output is:
30
60
150
2. Syntax of Varargs
The basic syntax is:
returnType methodName(dataType... parameterName) {
// method body
}
For example:
public static void display(int... numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
Here:
-
intis the data type. -
...indicates that the parameter is a varargs parameter. -
numbersis the parameter name. -
The method can receive any number of integer values.
3. How Varargs Work
Internally, Java treats a varargs parameter as an array.
Consider:
public static void display(int... numbers) {
System.out.println(numbers.length);
}
The following call:
display(10, 20, 30);
is essentially handled as an array containing:
10
20
30
Therefore, you can use array operations with a varargs parameter.
For example:
public static void display(int... numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
Calling:
display(5, 10, 15);
produces:
5
10
15
4. Passing Zero Arguments
One important feature of varargs is that you can pass zero arguments.
public static void display(int... numbers) {
System.out.println("Number of values: " + numbers.length);
}
You can call:
display();
Output:
Number of values: 0
This is different from a normal parameter, which generally requires a value when calling the method.
5. Passing One Argument
You can also pass just one value:
display(100);
The varargs array contains one element.
Conceptually:
[100]
The length is therefore 1.
6. Passing Multiple Arguments
You can pass as many values as required:
display(10, 20, 30, 40, 50);
The method receives them as an array:
[10, 20, 30, 40, 50]
This makes varargs particularly useful for calculations such as totals, averages, maximum values, and minimum values.
7. Example: Finding the Sum
public class VarargsExample {
public static int calculateSum(int... numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
public static void main(String[] args) {
System.out.println(calculateSum(10, 20));
System.out.println(calculateSum(10, 20, 30));
System.out.println(calculateSum(5, 10, 15, 20, 25));
}
}
Output:
30
60
75
The same calculateSum() method handles all three cases.
8. Varargs with Other Parameters
A method can have regular parameters along with a varargs parameter.
For example:
public static void display(String name, int... marks) {
System.out.println("Student: " + name);
for (int mark : marks) {
System.out.println(mark);
}
}
It can be called as:
display("Rahul", 80, 85, 90);
Output:
Student: Rahul
80
85
90
Here, name is a normal parameter and marks is a variable-length parameter.
9. Varargs Must Be the Last Parameter
The varargs parameter must always be the last parameter in a method declaration.
Correct:
public static void test(String name, int... values) {
}
Incorrect:
public static void test(int... values, String name) {
}
The second declaration produces a compilation error because Java cannot determine where the variable-length arguments end and the String parameter begins.
Therefore, the following structure should be remembered:
method(normalParameter, varargsParameter)
10. Only One Varargs Parameter Is Allowed
A method cannot have two varargs parameters.
Incorrect:
public static void test(int... numbers, String... names) {
}
Java does not allow this because it would be ambiguous when determining which arguments belong to which varargs parameter.
A method can have only one varargs parameter, and it must be the final parameter.
11. Varargs and Arrays
Because Java internally represents varargs as an array, you can pass an existing array to a varargs method.
For example:
public static void display(int... numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
You can create an array:
int[] values = {10, 20, 30, 40};
Then pass it to the method:
display(values);
This works because int... is treated as int[] internally.
12. Varargs with Different Data Types
Varargs can be used with different data types.
For example, with String:
public static void printNames(String... names) {
for (String name : names) {
System.out.println(name);
}
}
Calling:
printNames("Amit", "Ravi", "Priya");
Output:
Amit
Ravi
Priya
Similarly, you can use:
double...
float...
boolean...
and other valid Java types.
13. Varargs with Objects
Varargs can also accept objects.
For example:
public static void printStudents(Student... students) {
for (Student student : students) {
System.out.println(student);
}
}
This allows a method to work with any number of Student objects.
14. Varargs and Method Overloading
Varargs can also participate in method overloading.
For example:
public static void display(int a) {
System.out.println("Normal parameter");
}
public static void display(int... numbers) {
System.out.println("Varargs parameter");
}
If you call:
display(10);
Java chooses the method with the fixed parameter:
Normal parameter
A fixed-parameter method is generally preferred over a varargs method when both are applicable.
However, excessive overloading with varargs can make method selection confusing, so it should be designed carefully.
15. Example: Finding the Largest Number
Varargs are useful for finding the largest value among an unknown number of values.
public static int findLargest(int... numbers) {
int largest = numbers[0];
for (int number : numbers) {
if (number > largest) {
largest = number;
}
}
return largest;
}
Calling:
System.out.println(findLargest(10, 25, 15, 40, 30));
Output:
40
16. Advantages of Varargs
Varargs provide several advantages:
Reduced code:
There is no need to create separate methods for different numbers of arguments.
Improved flexibility:
A method can accept zero, one, or many arguments.
Better readability:
The method call is generally easier to understand.
Array compatibility:
An existing array can be passed directly to a varargs method.
Useful for utility methods:
Methods that calculate totals, averages, maximum values, or process multiple objects can benefit from varargs.
17. Limitations of Varargs
Although varargs are convenient, they should not be used unnecessarily.
The main limitations are:
-
Only one varargs parameter can exist in a method.
-
The varargs parameter must be the last parameter.
-
Since arguments are handled as an array, an array is created for the variable arguments.
-
Overusing varargs in overloaded methods can create ambiguity or unexpected method selection.
-
A varargs method may not be the best choice when the number of parameters is logically fixed.
18. Varargs Example with a Complete Program
public class VarargsDemo {
public static double calculateAverage(double... numbers) {
if (numbers.length == 0) {
return 0;
}
double total = 0;
for (double number : numbers) {
total += number;
}
return total / numbers.length;
}
public static void main(String[] args) {
System.out.println(calculateAverage(10, 20, 30));
System.out.println(calculateAverage(10, 20, 30, 40, 50));
}
}
Output:
20.0
30.0
Here, the method can calculate the average regardless of how many values are supplied.
19. Varargs vs Normal Parameters
| Feature | Normal Parameter | Varargs Parameter |
|---|---|---|
| Number of arguments | Usually fixed | Variable |
| Syntax | int number |
int... numbers |
| Zero arguments | Usually not possible | Possible |
| Multiple arguments | Requires multiple parameters | Directly supported |
| Internal representation | Individual value | Array |
| Position | Can occur anywhere | Must be last |
| Number per method | Multiple allowed | Only one varargs parameter |
20. Key Points to Remember
Varargs allow a Java method to receive a variable number of arguments. They are written using three dots (...) after the data type. Internally, Java treats the varargs parameter as an array, which means array properties such as length and array iteration can be used.
The most important rules are:
dataType... parameterName
A varargs parameter:
-
Can receive zero or more arguments.
-
Is internally treated as an array.
-
Must be the last parameter.
-
Can occur only once in a method.
-
Can accept an existing array.
-
Can be used with primitive types and objects.
-
Is useful when the number of arguments is not known beforehand.
In practical Java programming, varargs are especially useful for utility methods, mathematical calculations, logging-style methods, object processing, and APIs where the number of inputs can vary.