Can var-args only be used as a method argument?

This compiles fine: -

public class Demo {

    public static void main(String... args) {

    }
}

      

But this is not compiled.

public class Demo {

    public static void main(String... args) {
        String... strVarArgs ;

        //here i initiallize strVarArgs by some logic, like we do for arrays
    }
}

      

Plz correct me if I am syntactically wrong. : -)


cletus wrote: - This is really just syntactic sugar for an array

Here is an example followed by an expression from a very popular java book written by Katie Sierra and Bert Bates (Head First Java, 2nd Edition, McGraw-Hill / Osborne) : -

General topic themes,

<T extends MyClass>

where MyClass is a class and

<T extends MyInterface>

where MyInterface is an interface.

Following is a copy from the book (page 548, chapter 16): -

In generics, "extends means" "distributed or implemented" ??? The java engineers should have given you the ability to set a constraint on a parameterized type so that you can constrain it. But you also need to constrain the type to only allow classes that implement a specific interface. So, here's a situation where we need one kind of syntax to work in situations - inheritance and implementation. In other words, it works for both continuation and implementation. And the word of victory was ... continues. Whenever the Sun Engineer has the option to reuse an existing keyword since they are here with an extension, they usually do it. But sometimes they have no choice ... (assert, enum).

MyQuestion: Is var-args the syntactic sugar of an array without any other functions, then an array ???

+2


source to share


2 answers


Yes, varargs only applies to function arguments.

This is really just syntactic sugar for an array, so instead of:

String... strVarArgs ;

      



Do you want to

String strVarArgs[];

      

+3


source


Example:

public class VargArgsExample {

public static void printArgs(long requiredLongArgument, String... notRequiredStringArray) {
    System.out.println(requiredLongArgument);
    if (notRequiredStringArray != null) {
        for(String arg: notRequiredStringArray) {
            System.out.println(arg);
        }
    }
}

public static void main(String[] args) {
    printArgs(1L);
    printArgs(1L, "aa");
    printArgs(1L, "aa", "bb");
}

      

}



As you can see this syntax, sugar allows us to call methods without specifying the varargs argument . If no vararg argument is passed than null.

There is no need for another way of declaring a variable, so it is not used for that. This is why you are getting compile time error.

+1


source







All Articles