If I have a vararg Java method foo(Object ...arg)
and I call foo(null, null)
, I have both arg[0]
and arg[1]
as null
s. But if I call foo(null)
, arg
itself is null. Why is this happening?
How should I call foo
such that foo.length == 1 && foo[0] == null
is true
?
As Java cannot determine the type of literal null , you must explicitly inform the type of the literal null to Java. Failing to do so will result in an NullPointerException .
Yes. If you call it with an argument with a compile-time type of String , the compiler knows that can't be a String[] , so it wraps it within a string array. So this: String x = null; testNull(x);
While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.
Syntax of Varargs A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments.
The issue is that when you use the literal null, Java doesn't know what type it is supposed to be. It could be a null Object, or it could be a null Object array. For a single argument it assumes the latter.
You have two choices. Cast the null explicitly to Object or call the method using a strongly typed variable. See the example below:
public class Temp{ public static void main(String[] args){ foo("a", "b", "c"); foo(null, null); foo((Object)null); Object bar = null; foo(bar); } private static void foo(Object...args) { System.out.println("foo called, args: " + asList(args)); } }
Output:
foo called, args: [a, b, c] foo called, args: [null, null] foo called, args: [null] foo called, args: [null]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With