开发者

Is var-args can be used as method argument only?

This is compiling fine :-

public class Demo {

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

    }
}

But this is not getting 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 :- It's really just syntactic sugar for an array

Here is an example followed by a statement from a very popular java book written by Kathy Sierra and Bert Bates (Head First Java, 2nd Edition, McGra开发者_如何转开发w-Hill/Osborne) :-

Topic generics,

<T extends MyClass>, where MyClass is a class, and

<T extends MyInterface>, where MyInterface is an interface.

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

In generics, "extends means" "extends or implements"??? The java engineers had to give you a way to put a constraint on a parameterized type, so that you can restrict it to. But you also need to constrain a type to allow only classes that implement a particular interface. So, here's a situation where we need one kind of syntax to work for both situations-inheritence and implementation. In other words, that works for both extends and implementations. And the winning word was ...extends. Whenever there's a chance for the sun engineer's to reuse an existing keyword, as they did here with "extends", they will usually do that. But sometimes they don't have a choice...(assert, enum).

MyQuestion : Is var-args just a syntactic sugar of array, with no other features then array???


Yes, varargs only applies to function arguments.

It's really just syntactic sugar for an array so instead of:

String... strVarArgs ;

you want

String strVarArgs[];


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 specifing varargs argument. If no vararg argument is passed than it is null.

There is no need in just another way of variable declaration, so it is not used for it. And that is why you're getting compile-time error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜