DEV Community

Aswin Arya
Aswin Arya

Posted on

What Are Varargs in Java? A Complete Guide

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
}
Enter fullscreen mode Exit fullscreen mode

🔹 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
    }
}
Enter fullscreen mode Exit fullscreen mode

👉 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)
Enter fullscreen mode Exit fullscreen mode

👉 is internally treated as:

void method(int[] nums)
Enter fullscreen mode Exit fullscreen mode

🔹 Rules of Varargs

✅ 1. Only One Varargs Parameter Allowed

void test(int... a, int... b)  // not allowed
Enter fullscreen mode Exit fullscreen mode

✅ 2. Must Be the Last Parameter

void test(int a, int... b) 
void test(int... a, int b) 
Enter fullscreen mode Exit fullscreen mode

✅ 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 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) {}
Enter fullscreen mode Exit fullscreen mode

With Varargs:

void add(int... numbers) {}
Enter fullscreen mode Exit fullscreen mode

👉 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)