javaarraysjava-5

Can you pass no Values to a Java Parameter Array


Most people should know of the Object... objs way of having an array as a parameter. Essentially it's just Object[] objs. However I found something, where you can't match the functionality. (Or I just don't know how)

//  How does one go about calling this method?
void test(String s, String... strings, String s2) {}

And how would you accomplish this with the ... syntax?

public static void main(String[] args) {
    foo(new String[] {}); //  foo(new String[0]);
}

static void foo(String[] s) {}

Solution

  • You can do something like this

    //  How does one go about calling this method?
    void test(String s, String s2, String... strings) {}
    

    but this is not a valid

    //  How does one go about calling this method?
    void test(String s, String... strings, String s2) {}
    

    an excerpt from https://www.baeldung.com/java-varargs

    varargs are straightforward to use. But there're a few rules we have to keep in mind:

    • Each method can only have one varargs parameter
    • The varargs argument must be the last parameter