Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Java varargs method with single null argument?

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 nulls. 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?

like image 891
pathikrit Avatar asked Oct 26 '10 21:10

pathikrit


People also ask

Can Java Varargs be null?

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 .

Can Varargs be empty?

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);

What is the rule for using varargs in Java?

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.

Can Varargs take 0 arguments?

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.


1 Answers

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] 
like image 117
Mike Deck Avatar answered Oct 02 '22 05:10

Mike Deck