Variable Arguments (Varargs)
Variable Arguments (Varargs) in Java allow a method to accept zero or more arguments of the same type. They were introduced in Java 5 to simplify method calls when the number of arguments is not fixed. This is a frequent interview topic, especially in relation to method overloading and arrays.
What Are Varargs?
- Allow passing multiple values to a method
- Internally treated as an array
- Simplify method calls
- Reduce method overloading
int sum(int... numbers) {
// numbers is an int[]
}
Basic Syntax
returnType methodName(dataType... variableName) {
// method body
}
Simple Example
int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
Method Calls
sum(); // 0 arguments
sum(10); // 1 argument
sum(10, 20, 30); // multiple arguments
Varargs Are Treated as Arrays
void display(String... values) {
System.out.println(values.length);
}
- values is internally a String[]
- Can use loops and array operations
Varargs with Fixed Parameters
Varargs must be the last parameter.
void show(String name, int... marks) { }
// ✔ Valid
void show(int... marks, String name) { } // ❌ Invalid
Varargs with One Fixed Parameter Example
void printDetails(String name, int... scores) {
System.out.println("Name: " + name);
for (int s : scores) {
System.out.println(s);
}
}
Varargs vs Method Overloading
Without Varargs
int add(int a, int b) { }
int add(int a, int b, int c) { }
With Varargs
int add(int... nums) { }
// ✔ Cleaner and scalable
Varargs with Method Overloading (Ambiguity)
void test(int a, int... b) { }
void test(int... a) { }
// test(10); // Compile-time ambiguity
⚠️ Use carefully.
Passing Array to Varargs
int[] arr = {1, 2, 3};
sum(arr);
// ✔ Valid
Varargs with main() Method
public static void main(String... args) {
System.out.println(args.length);
}
// ✔ Valid alternative to String[] args
Varargs and Performance
- Slight overhead due to array creation
- Not suitable for performance-critical loops
- Fine for normal usage
Common Rules to Remember (Very Important)
- Only one varargs parameter per method
- Varargs must be the last parameter
- Varargs can accept zero arguments
- Treated internally as an array
Common Beginner Mistakes
- Placing varargs before other parameters
- Creating ambiguous overloaded methods
- Forgetting zero-argument case
- Assuming varargs is faster than arrays
Interview-Ready Answers
Short Answer
Varargs allow a method to accept a variable number of arguments of the same type.
Detailed Answer
In Java, varargs enable methods to take zero or more arguments and are internally implemented as arrays. They simplify method calls and reduce the need for multiple overloaded methods, but must be declared as the last parameter.
Key Takeaway
Varargs make method signatures flexible and clean, but should be used carefully to avoid ambiguity and unnecessary overhead.