Java List to varargs

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.

Need of Java Varargs

  • Until JDK 4, we cant declare a method with variable no. of arguments. If there is any change in the number of arguments, we have to declare a new method. This approach increases the length of the code and reduces readability.
  • Before JDK 5, variable-length arguments could be handled in two ways. One uses an overloaded method(one for each), and another puts the arguments into an array and then passes this array to the method. Both of them are potentially error-prone and require more code. 
  • To resolve these problems, Variable Arguments (Varargs) were introduced in JDK 5. From JDK 5 onwards, we can declare a method with a variable number of arguments. Such types of methods are called Varargs methods. The varargs feature offers a simpler, better option.

Syntax of Varargs

Internally, the Varargs method is implemented by using the single dimensions arrays concept. Hence, in the Varrargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). 

For Example, 

public static void fun(int ... a) { // method body }

This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].

Below is a code snippet for illustrating the above concept :

class Test1 {

    static void fun(int... a)

    {

        System.out.println("Number of arguments: "

                           + a.length);

        for (int i : a)

            System.out.print(i + " ");

        System.out.println();

    }

    public static void main(String args[])

    {

        fun(100);

        fun(1, 2, 3, 4);

          fun();

    }

}

OutputNumber of arguments: 1 100 Number of arguments: 4 1 2 3 4 Number of arguments: 0

Explanation of the above program

  • The … syntax tells the compiler that varargs have been used, and these arguments should be stored in the array referred to by a.
  • The variable a is operated on as an array. In this case, we have defined the data type of an array ‘a’ as int. So it can take only integer values. The number of arguments can be found out using a.length, the way we find the length of an array in Java.

Note: A method can have variable length parameters with other parameters too, but one should ensure that there exists only one varargs parameter that should be written last in the parameter list of the method declaration. For example:

int nums(int a, float b, double … c)

In this case, the first two arguments are matched with the first two parameters, and the remaining arguments belong to c.

class Test2 {

    static void fun2(String str, int... a)

    {

        System.out.println("String: " + str);

        System.out.println("Number of arguments is: "

                           + a.length);

        for (int i : a)

            System.out.print(i + " ");

        System.out.println();

    }

    public static void main(String args[])

    {

        fun2("GeeksforGeeks", 100, 200);

        fun2("CSPortal", 1, 2, 3, 4, 5);

        fun2("forGeeks");

    }

}

OutputString: GeeksforGeeks Number of arguments is: 2 100 200 String: CSPortal Number of arguments is: 5 1 2 3 4 5 String: forGeeks Number of arguments is: 0

Erroneous Varargs Examples

Case 1: Specifying two Varargs in a single method: 

void method(String... gfg, int... q) { // Compile time error as there // are two varargs }

Case 2: Specifying Varargs as the first parameter of the method instead of the last one: 

void method(int... gfg, String q) { // Compile time error as vararg // appear before normal argument }

Important Points regarding Varargs

  • Vararg Methods can also be overloaded, but overloading may lead to ambiguity.
  • Before JDK 5, variable length arguments could be handled in two ways: One was using overloading, other was using array argument.
  • There can be only one variable argument in a method.
  • Variable argument (Varargs) must be the last argument.

This article is contributed by Niraj Srimal. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

In java, you can create a method that takes variable number of arguments. This feature is called varargs or variable number of arguments. Method which accepts variable number of arguments is called varargs method.

Syntax

returnType methodName(dataType … parameterName){

}

"..." tells the compiler that this is a vararg.

For example, ‘printInfo’ method takes varargs of string as argument and prints.

private static void printInfo(String... data) {

    for (String str : data) {

        System.out.println(str);

    }

}

Since printInfo takes an array as argument, you can convert the list to an array and call this method like below.

printInfo(countries.toArray(new String[countries.size()]));

App.java

package com.sample.app; import java.util.Arrays; import java.util.List; public class App { private static void printInfo(String... data) { for (String str : data) { System.out.println(str); } } public static void main(String args[]) { List<String> countries = Arrays.asList("India", "Sri Lanka", "Singapore", "Australia"); printInfo(countries.toArray(new String[countries.size()])); } }

Output

India

Sri Lanka

Singapore

Australia

You may like

Miscellaneous

Interview Questions

Programming Questions

Capitalize first letter of every word in string

Can an Anonymous class has an explicit constructor?

How Java handles Integer overflows and underflows?

Thread.start() vs Runnable.run()