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.
Rules of Varargs in Java
7.
Example of Varargs in Java
7.1.
Java
7.2.
Output
8.
Erroneous Varargs Examples
8.1.
Java
9.
Overloading Varargs Methods
9.1.
Java
10.
Working of Java Varargs
11.
Advantages of Varargs in Java
12.
Important Points regarding Varargs
13.
Frequently Ask Questions
13.1.
What is a Varargs in Java?
13.2.
Can we have 2 Varargs in Java?
13.3.
What is difference between array and Varargs?
13.4.
Which data structure is used by Varargs in Java?
14.
Conclusion
Last Updated: Mar 27, 2024
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.

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.

Overloading Varargs Methods

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.

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.


Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! You can also consider our paid courses such as DSA in Java to give your career an edge over others.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass