Table of contents
1.
Introduction
2.
What is Java Varargs?
3.
​​Importance of Java Varargs
4.
Syntax of Varargs
5.
Need of Java Varargs
6.
Why Use Variable Arguments in Java?
7.
Rules of Varargs in Java
8.
Example of Varargs in Java
8.1.
Java
8.2.
Output
9.
Erroneous Varargs Examples
9.1.
Java
10.
Method Overloading with Varargs
10.1.
Java
11.
Working of Java Varargs
12.
Advantages of Varargs in Java
13.
Important Points regarding Varargs
14.
Real-World Use Cases of Varargs
15.
Frequently Ask Questions
15.1.
What is a Varargs in Java?
15.2.
Can we have 2 Varargs in Java?
15.3.
What is difference between array and Varargs?
15.4.
Which data structure is used by Varargs in Java?
16.
Conclusion
Last Updated: Jul 3, 2025
Medium

Varargs in Java(Variable Arguments)

Author Muskan Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Varargs, also known as variable arguments, is a Java method that accepts a flexible number of inputs. It simplifies methods needing varying argument counts. 

Varargs in Java(Variable Arguments)

Also see, Duck Number in Java

What is Java Varargs?

The Java varargs notion is a feature of the Java programming language that makes it easier to create methods that can accept a variable number of arguments. The short word for variable-length opinions is varargs, which refers to this feature or notion. A varargs method will take a variable number of arguments in this case. There are two ways to handle varargs(variable-length arguments) before the JDK 5 version.

The overloaded method can be used as one method, and an array can be passed to the method in place of the arguments as a second option.

​​Importance of Java Varargs

There are several reasons why Varargs is required: 

  • Variable Argument List: Varargs, short for variable-length argument lists, allows methods to accept a variable number of arguments. This flexibility simplifies method calls, making them adaptable to different use cases.
     
  • Simplified Method Overloading: Varargs reduce the need for method overloading. Instead of creating multiple methods with different parameter counts, a single method with varargs can handle varying argument lengths.
     
  • Conciseness and Readability: Varargs provide a concise syntax, enhancing code readability. They eliminate the need for explicitly creating arrays or lists when passing multiple arguments to a method.
     
  • Reduced Boilerplate Code: Varargs help reduce boilerplate code associated with creating and passing arrays explicitly. This leads to cleaner and more maintainable code.
     
  • Enhanced Flexibility: Developers can pass any number of arguments when using varargs, providing enhanced flexibility. This is particularly useful in scenarios where the exact number of arguments may vary.

Syntax of Varargs

Below is the syntax of the Varargs syntax:

public static void Varargs_fun(int …variable){
	/* Here is the body of the function */
}


In the above code, the parameter "variable" is used to generate the Varargs_fun() method. The method body will then be entered for usage during execution. In the particular method, just one variable named arg-arguments should be used. To prevent compilation, the varargs - variable-length argument must come last.

Must Read Static Blocks In Java

Need of Java Varargs

Here are some importance of using Varargs in Java.

  • Before JDK 5, there were two ways to handle variable-length parameters: one was to use an overloaded method, and the other was to place the arguments in an array and then send the array to a method.
     
  • JDK 4 is necessary for us to declare a method in Java with various arguments. If there were alterations, new techniques were developed. As a result, the code's length increased, making reading challenging. Varargs was introduced to address these problems.
     
  • To address these issues, JDK introduced vararags, which enabled the declaration of methods with a variable amount of arguments. It is by far the best and most straightforward choice.

Why Use Variable Arguments in Java?

Variable arguments (varargs) in Java provide a powerful way to handle methods that need to accept a flexible number of inputs. Introduced in Java 5, varargs eliminate the need for repetitive code and make APIs more dynamic and developer-friendly. Below are the three main reasons why use varargs in Java:

1. Simplifies Method Definitions
Using varargs allows developers to pass multiple arguments to a method without defining overloaded versions. Instead of writing several methods like add(int a, int b), add(int a, int b, int c), and so on, a single method like add(int... numbers) can handle all cases. This not only simplifies the code but also makes it easier to write and understand. The compiler automatically wraps the passed arguments into an array, making varargs both powerful and convenient.

 

2. Improves Code Readability and Reusability
Varargs improve code clarity by reducing clutter caused by multiple method definitions for varying input lengths. With just one method that accepts varargs, you can handle zero, one, or many arguments. This approach leads to cleaner, more reusable code that's easier to maintain. Developers can quickly understand the method's intent without navigating through multiple overloads, enhancing both readability and maintainability.
 

3. Enables Flexible API Design
One of the key advantages of varargs is their role in creating flexible and user-friendly APIs. Standard Java methods like String.format(), System.out.printf(), and Arrays.asList() use varargs to accept dynamic input lengths. This flexibility allows developers to use these methods in a wide range of scenarios, making the API feel intuitive and efficient. By incorporating varargs, you can design methods that are both powerful and adaptable.

Rules of Varargs in Java

When working with varargs, adherence to specific rules is essential to ensure successful compilation of the program code. These rules include:

  • Restriction to a single variable argument in the method
     
  • Mandatory placement of the varargs as the last argument
     
  • You cannot declare a varargs parameter with an empty argument list
     
  • To declare a varargs parameter, use an ellipsis (...) followed by the argument type in the method's parameter list
     
  • You can call the method with zero or more arguments of the specified type

Example of Varargs in Java

  • Java

Java

class CodingNinjas {
   static void vararges_fun(int...variable) {
       System.out.println("The number of mentioned arguments is as follows: " + variable.length);
       for (int i1: variable)
           System.out.println(i1 + " ");
       System.out.println();
   }
   public static void main(String args[]) {


       // Passing one parameter.
       vararges_fun(100);


       // Passing one parameter.
       vararges_fun();


       // Passing one parameter.
       vararges_fun(10, 20, 30, 40);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Output

You can also read about the topic of Java Destructor

Erroneous Varargs Examples

Here are erroneous Java varargs examples:

Incorrect Placement of Varargs: In this example, the varargs are not placed at the end of the parameter list. In Java, varargs must be the last parameter, and having parameters after them will result in a compilation error.

  • Java

Java

class ErroneousExample {
public static void printValues(int... numbers, String message) {
for (int num : numbers) {
System.out.println(num);
}
System.out.println(message);
}

public static void main(String[] args) {
printValues(1, 2, 3, "Varargs Example"); // Compilation error
}
}
You can also try this code with Online Java Compiler
Run Code

Output

output

Explanation:

The compiler will generate an error stating "varargs must be the last parameter" because the String message parameter follows the varargs parameter int... numbers.

Passing Array as Varargs: In this example, an attempt is made to pass an array directly to a varargs parameter. However, this results in a compilation error.

public class ErroneousExample {
    public static void printValues(String... messages) {
        for (String message : messages) {
            System.out.println(message);
        }
    }

    public static void main(String[] args) {
        String[] messageArray = {"Hello", "Varargs"};
        printValues(messageArray); // Compilation error
    }
}


Explanation:

Although varargs can accept multiple arguments, attempting to pass an array directly to varargs is not allowed. The correct way is to pass each element of the array separately.

Method Overloading with Varargs

Overloading varargs methods refers to the practice of defining multiple methods in Java that have the same name but differ in the number or type of varargs arguments they accept. This allows developers to create flexible and versatile methods that can handle varying numbers of arguments, enhancing code reusability and readability. Varargs methods provide a convenient way to work with variable-length argument lists in Java. For example:

  • Java

Java

public class Main {

private void test(int... args) {
int multiple = 1;
for (int i : args) {
multiple *= i;
}
System.out.println("Multiplication of the numbers = " + multiple);
}

private void test(boolean b, String... args) {
boolean check = !b;
System.out.println("Result = " + check);
System.out.println("args.length = " + args.length);
}

public static void main(String[] args) {
Main obj = new Main();
obj.test(2, 4, 8);
obj.test(false, "hello", "ninjas");
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

output

Working of Java Varargs

When using varargs, the three dots (...) syntax instructs the compiler to save the arguments in the array. The Java compiler constructs an array of the remaining arguments when it reaches the final varargs parameter when we call a method with variable parameters. This array is then passed to the method. The varargs parameter represents an array of the provided type.

Check out this article - Upcasting and Downcasting in Java.

Advantages of Varargs in Java

The advantages of varargs in Java are mentioned below:

  • They allow methods to accept a variable number of arguments, making it easier to work with methods that need to handle different numbers of inputs
     
  • They simplify method calls by allowing developers to pass multiple arguments as a comma-separated list, instead of creating an array or list
     
  • They improve code readability by eliminating the need for manual array creation and initialization when passing multiple arguments
     
  • These methods can be overloaded to handle different argument combinations, enhancing code reusability
     
  • They reduce the amount of boilerplate code required to pass variable-length argument lists

Important Points regarding Varargs

  • Varargs must always be the last parameter in a method's parameter list.
     
  • Varargs can only be used for the last parameter in a method signature.
     
  • The Varargs parameter is treated as an array within the method.
     
  • Varargs can accept zero or more arguments of the specified type.
     
  • If needed, methods with Varargs can be overloaded with methods that have a different number of parameters.
     
  • Varargs provide a convenient way to pass a variable number of arguments without explicitly creating an array.
     
  • Varargs can be used with different types, such as int, String, Object, etc.
     
  • When invoking a method with Varargs, you can pass individual values or an array of values of the specified type.
     
  • Varargs can be combined with other parameters in a method signature to create methods with more flexible argument options.
     
  • It's important to handle cases where no arguments are passed when using Varargs to avoid potential NullPointerExceptions.
     

You can also check about Java Tokens here.

Real-World Use Cases of Varargs

Understanding real-world use of varargs in Java helps developers see the true value of this flexible feature. Beyond simplifying method design, varargs power many widely-used methods in the Java standard library and enterprise frameworks. Below are two practical examples that show how varargs are used effectively in real development scenarios.

1. Logging Methods
Logging frameworks often rely on varargs to handle dynamic message formatting. For example, methods like Logger.log(String format, Object... args) or System.out.printf() use varargs to accept any number of arguments, making log generation more dynamic and readable.

System.out.printf("User %s logged in at %s%n", "Alice", "10:45 AM");


Here, the %s placeholders are replaced by the values passed via varargs. This approach avoids string concatenation and supports structured logging. Whether logging two variables or ten, you don’t need multiple method overloads. This is a key Java varargs example that boosts flexibility and code cleanliness in logging scenarios.

 

2. Utility Libraries (e.g., String.format(), Arrays.asList())
Several standard Java utility methods use varargs to offer cleaner and more adaptable APIs. The String.format() method, for example, accepts a format string followed by a variable number of arguments.

String message = String.format("Hello %s, you have %d new messages.", "Bob", 5);


Similarly, Arrays.asList() takes any number of elements and returns a list:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");


These methods show how varargs simplify method usage by accepting flexible input sizes without needing separate methods. Such real-world use of varargs in Java helps developers write concise and maintainable code across different scenarios.

Frequently Ask Questions

What is a Varargs in Java?

Varargs (Variable-Length Argument Lists) in Java allow methods to accept a variable number of arguments. It simplifies method calls by handling multiple parameters dynamically.

Can we have 2 Varargs in Java?

No, Java allows only one varargs parameter per method, and it must be the last parameter.

What is difference between array and Varargs?

Arrays are fixed in size, while varargs provide flexibility by accepting a variable number of arguments. Varargs simplify method calls without explicitly creating arrays.

Which data structure is used by Varargs in Java?

Varargs use an array as the underlying data structure to store the variable-length argument list passed to a method.

Conclusion

You understand the correct meaning of Java varargs, their syntax, and explanation, how the varargs function in the Java programming language, and many instances of implementing the varargs idea.

Below are the mentioned kike that will help you out in gaining more knowledge in JAVA.

Live masterclass