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.
Varargs Examples (Quick Reference)
1. Basic Varargs Method
class Demo {
static void sum(int... nums) {
int total = 0;
for (int n : nums) {
total += n;
}
System.out.println(total);
}
public static void main(String[] args) {
sum(1, 2, 3);
}
}
Explanation: Varargs treated as array.
Output: 6
2. Calling Varargs with No Arguments
class Demo {
static void show(int... nums) {
System.out.println(nums.length);
}
public static void main(String[] args) {
show();
}
}
Explanation: Creates empty array.
Output: 0
3. Varargs with Single Argument
class Demo {
static void print(int... nums) {
System.out.println(nums[0]);
}
public static void main(String[] args) {
print(10);
}
}
Explanation: Works like one-element array.
Output: 10
4. Varargs Internally Is an Array
class Demo {
static void test(int... nums) {
System.out.println(nums.getClass().getName());
}
public static void main(String[] args) {
test(1, 2);
}
}
Explanation: Varargs compiled as array.
Output: [I
5. Passing Array to Varargs Method
class Demo {
static void show(int... nums) {
for (int n : nums) System.out.print(n + " ");
}
public static void main(String[] args) {
int[] a = {1, 2, 3};
show(a);
}
}
Explanation: Array fits varargs.
Output: 1 2 3
6. Varargs Must Be Last Parameter
class Demo {
static void test(String name, int... nums) {
System.out.println(name);
}
// static void test(int... nums, String name) ❌
}
Explanation: Compile-time rule. Varargs must be last.
7. Only One Varargs Allowed
class Demo {
// static void test(int... a, int... b) ❌
}
Explanation: Only one varargs parameter allowed per method.
8. Varargs with Other Parameters
class Demo {
static void show(String msg, int... nums) {
System.out.println(msg + " " + nums.length);
}
public static void main(String[] args) {
show("Count:", 1, 2, 3);
}
}
Explanation: Normal parameters first.
Output: Count: 3
9. Varargs in Method Overloading (Exact Match Wins)
class Demo {
static void show(int a) {
System.out.println("int");
}
static void show(int... a) {
System.out.println("varargs");
}
public static void main(String[] args) {
show(5);
}
}
Explanation: Exact match preferred.
Output: int
10. Overloading Varargs vs Array
class Demo {
static void show(int[] a) {
System.out.println("array");
}
static void show(int... a) {
System.out.println("varargs");
}
public static void main(String[] args) {
show(new int[]{1, 2});
}
}
Explanation: Array is more specific.
Output: array
11. Varargs and Autoboxing
class Demo {
static void show(Integer... nums) {
System.out.println(nums.length);
}
public static void main(String[] args) {
show(1, 2, 3);
}
}
Explanation: Autoboxing applies.
Output: 3
12. Varargs with null Argument
class Demo {
static void show(int... nums) {
System.out.println(nums);
}
public static void main(String[] args) {
show(null);
}
}
Explanation: null treated as array reference. Throws NullPointerException on access.
13. Avoiding NullPointerException in Varargs
class Demo {
static void show(int... nums) {
if (nums == null) {
System.out.println("Null array");
return;
}
System.out.println(nums.length);
}
public static void main(String[] args) {
show(null);
}
}
Explanation: Defensive coding.
Output: Null array
14. Varargs in Enhanced for-loop
class Demo {
static void display(String... values) {
for (String s : values) {
System.out.print(s + " ");
}
}
public static void main(String[] args) {
display("Java", "Selenium", "API");
}
}
Explanation: Easy iteration.
Output: Java Selenium API
15. Varargs with Generic Type
class Demo {
static <T> void print(T... items) {
for (T t : items) {
System.out.print(t + " ");
}
}
public static void main(String[] args) {
print(1, "Java", 3.5);
}
}
Explanation: Generic varargs.
Output: 1 Java 3.5
16. Varargs Used for Logging Utility
class Logger {
static void log(String level, String... messages) {
for (String msg : messages) {
System.out.println(level + ": " + msg);
}
}
public static void main(String[] args) {
log("INFO", "Started", "Running", "Completed");
}
}
Explanation: Real-world usage.
Output:
INFO: Started
INFO: Running
INFO: Completed
17. Varargs with Method Chaining
class Demo {
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static void main(String[] args) {
System.out.println(sum(1, 2) + sum(3, 4));
}
}
Explanation: Returns value.
Output: 10
18. Varargs vs Overloading Confusion
class Demo {
static void show(int a, int b) {
System.out.println("two args");
}
static void show(int... a) {
System.out.println("varargs");
}
public static void main(String[] args) {
show(1, 2);
}
}
Explanation: Fixed arguments preferred.
Output: two args
19. Performance Note on Varargs
class Demo {
static void show(int... nums) {
// Creates array internally
}
}
Explanation: Avoid heavy use in performance-critical loops.
20. Interview Summary – Varargs
class Demo {
static void test(int... nums) {
nums[0] = 99;
}
public static void main(String[] args) {
int[] a = {1, 2};
test(a);
System.out.println(a[0]);
}
}
Explanation: Varargs is array reference.
Output: 99