当前位置:   article > 正文

java main参数null,Varargs在Java中使用null参数

java varargs null

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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/375117
推荐阅读
相关标签
  

闽ICP备14008679号