简体   繁体   中英

Varargs with null parameters in Java

The following code simply uses a null reference as a varargs parameter.

package currenttime;

import java.util.Arrays;

public class Main
{
    private static void temp(String...str)
    {
        System.out.println(Arrays.asList(str));
    }

    public static void main(String[] args)
    {
        temp(null,null);
        temp(null);
    }
}

The first call to the method temp(null, null); displays [null, null] means that str[0]=null and str[1]=null .

but the later call to temp(null); causes the NullPointerException to be thrown which appears that the str itself is null .

If it's type cast to String something like this temp((String)null); , it works and displays [null] .

Why in the last call, an explicit type cast is required? It seems to me that it's considered to be a string array with a null reference which is different from the first call. What is the correct answer?

It seems to me that it's considered to be a string array with a null reference which is different from the first call

Exactly. This is what happening.

Actually, it's just about precedence between: - exact-match , var-args , boxing and type-casting .

Compiler follow the following precedence when checking for methods to be called, or how the argument will be passed: -

Exact-Match > Type-Cast > Boxing > Var-args

So, you can see that, var-args has the lowest precedence, and exact-match has the highest precedence. That means, if an argument is good-enough for an exact-match then it will be considered as such.

Now, when you pass null as an argument, then null can directly be passed to your var-args parameter as the value of reference . It is an exact match for the parameter.
So, you need to typecast it explicitly to String to tell that its actually the first element of your var-args parameter

Whereas, in case of null, null , it will be taken as two elements of your var-args . As it cannot be a value of reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM