16

As I understand an array consists of fixed number of elements and a variable length argument takes as many number of arguments as you pass (of the same type). But are they same? Can I pass one where the other is expected?

  • 2
    Have you tried? It doesn't take much to write a few lines of Java. The answer is: *Yes*, you can also pass an array to a variable argument method and it will be used as the argument list. But *No*, you cannot pass variable arguments to a method that is declared to accept an array. – Erwin Bolwidt Apr 19 '14 at 09:43
  • @ErwinBolwidt Your comment is very helpful. Thank you. –  Apr 19 '14 at 09:52

3 Answers3

27

Yes, if you have a method with a varargs parameter like this:

public void foo(String... names)

and you call it like this:

foo("x", "y", "z");

then the compiler just converts that into:

foo(new String[] { "x", "y", "z"});

The type of the names parameter is String[], and can be used just like any other array variable. Note that it could still be null:

String[] nullNames = null;
foo(nullNames);

See the documentation for varargs for more information.

This does not mean that varargs are interchangeable with arrays - you still need to declare the method to accept varargs. For example, if your method were declared as:

public void foo(String[] names)

then the first way of calling it would not compile.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • As mentioned by ErwinBolwidt, we can can't pass variable number of arguments where an array is expected. But, what about main method? We can declare main as main(String... args) right? Can you please clarify? –  Apr 19 '14 at 09:58
  • @Phoenix: Yes, you can - as you can easily test for yourself, of course. – Jon Skeet Apr 19 '14 at 10:14
8

They are the same, array is internally used by JVM when creating varargs methods. So you can treat vararg argument in the same way you treat array so use for instance enhanced for loop

public void method(String... args) {
    for(String name : args) {
     //do something
     }
}

and call it like this or even pass an array

method("a", "b", "c"); 
method(new String[] {"a", "b", "c"});

See this nice article for further explanation.

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
5

A simple test would suggest that they are the same:

public class test {

    public static void varArgs(String... strings) {
        for (String s : strings) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        String[] strings = {"string1", "string2", "string3"};
        varArgs(strings);
        varArgs("string4", "string5", "string6");
    }
}

Outputs:

string1
string2
string3
string4
string5
string6
Sam G-H
  • 627
  • 6
  • 17
  • But a Java array's size must be preset. And that would limit the number of arguments allowed to the size of that array. Seems to me that the variable arguments list must be an ArrayList – Trunk Nov 05 '18 at 12:54