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?
Exactly. This is what happening.
Actually, it’s just about
precedencebetween: –exact-match,var-args,boxingandtype-casting.Compiler follow the following precedence when checking for methods to be called, or how the argument will be passed: –
So, you can see that,
var-argshas the lowest precedence, andexact-matchhas the highest precedence. That means, if anargumentisgood-enoughfor anexact-matchthen it will be considered as such.Now, when you pass
nullas an argument, thennullcan directly be passed to yourvar-argsparameter as thevalue of reference. It is anexact matchfor the parameter.So, you need to
typecastit explicitly toStringto tell that its actually the first element of yourvar-argsparameterWhereas, in case of
null, null, it will be taken astwoelements of yourvar-args. As it cannot be avalue of reference.