
1. Overview
In this article, we will learn to call Java varargs method with a single null argument.
2. Java varargs method with single null argument
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
.
For example, the following main method invokes the foo method with literal null
. There is no information on the argument type.
public static void main(String[] args){ foo(null); } private static void foo(Object...args) { System.out.println("Variable arguments : " + Arrays.asList(args)); }
If you execute the above code, it would result in the following error.
warning: non-varargs call of varargs method with inexact argument type for last parameter; foo(null); ^ cast to Object for a varargs call cast to Object[] for a non-varargs call and to suppress this warning 1 warning Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Arrays$ArrayList.<init>(Arrays.java:4137) at java.base/java.util.Arrays.asList(Arrays.java:4122) at Temp.foo(Temp.java:15) at Temp.main(Temp.java:7)
Now, let’s see the alternative ways to avoid this error and pass a null value as varargs
parameter.
2.1. Cast to Object for a Java varargs call
The first option is to cast the null
explicitly to the Object type.
public static void main(String[] args){ foo((Object) null); } private static void foo(Object...args) { System.out.println("Variable arguments : " + Arrays.asList(args)); } /* prints Variable arguments : [null] */
2.1. Strongly typed variable with null
The next option is to create a strongly typed variable and assign null
to it. Then, pass that variable as an argument to the varargs
.
public static void main(String[] args){ Object bar = null; foo(bar); } private static void foo(Object...args) { System.out.println("Variable arguments : " + Arrays.asList(args)); } /* prints Variable arguments : [null] */
2.2. Simply call with no argument
Alternatively, you can completely ignore passing null or any value to the vararg
.
For example, the following main method invokes the foo without passing any value to the varargs
parameter.
public static void main(String[] args){ foo(); } private static void foo(Object...args) { System.out.println("Variable arguments : " + Arrays.asList(args)); } /* prints Variable arguments : [] */
3. Conclusion
To sum up, we have learned to call Java varargs method with a null literal.