java main参数null,Varargs在Java中使用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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值