In Java, there are situations where you don’t know how many arguments a method will receive. Instead of writing multiple overloaded methods, Java provides a flexible feature called Varargs (Variable Arguments).
Let’s understand how varargs work and why they are useful.
🔹 What Are Varargs?
Varargs allow a method to accept zero or more arguments of the same type.
👉 It is declared using three dots ...
💡 Syntax:
void methodName(datatype... variableName) {
// method body
}
🔹 Simple Example
class Test {
static void printNumbers(int... numbers) {
for (int n : numbers) {
System.out.println(n);
}
}
public static void main(String[] args) {
printNumbers(10);
printNumbers(10, 20, 30);
printNumbers(); // no arguments
}
}
👉 The method works with any number of arguments!
🔹 How Varargs Work Internally
Behind the scenes, Java converts varargs into an array.
void method(int... nums)
👉 is internally treated as:
void method(int[] nums)
🔹 Rules of Varargs
✅ 1. Only One Varargs Parameter Allowed
void test(int... a, int... b) ❌ // not allowed
✅ 2. Must Be the Last Parameter
void test(int a, int... b) ✅
void test(int... a, int b) ❌
✅ 3. Can Be Combined with Normal Parameters
void display(String name, int... marks) {
System.out.println(name);
for (int m : marks) {
System.out.println(m);
}
}
🔹 Varargs vs Method Overloading
Without Varargs:
void add(int a, int b) {}
void add(int a, int b, int c) {}
void add(int a, int b, int c, int d) {}
With Varargs:
void add(int... numbers) {}
👉 Cleaner and reduces code duplication.
🔹 Real-Time Use Cases
Varargs are commonly used in:
- Logging frameworks
- Utility methods
- Print and formatting functions
- APIs where input size is dynamic
🔥 Advantages of Varargs
- ✅ Flexible number of arguments
- ✅ Cleaner and shorter code
- ✅ Reduces method overloading
- ✅ Easy to use
⚠️ Disadvantages
- ❌ Slight performance overhead (array creation)
- ❌ Can cause ambiguity with method overloading
🚀 Final Thoughts
Varargs make Java methods more flexible and developer-friendly. They are especially useful when dealing with dynamic input sizes and help keep your code clean and maintainable.
🎯 Learn More – Upgrade Your Java Skills
Join the Best Core JAVA Online Training in Hyderabad and gain hands-on experience with real-time projects, expert mentorship, and interview preparation.
Top comments (0)