Varargs with null parameters in Java

笑着哭i 提交于 2019-12-04 03:24:11

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!