Calling Java varargs method with single null argument?

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]

Leave a Comment