Can a Java varargs be null?
I tried it with Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0 on Linux 3.5.0-21-generic
Using myMethod(null)
doesn't pass new Object[]{null}
, it passes null
. Arrays are objects in Java and therefore null
is valid for the type Object[]
.
Your nullcheck is, therefore, not overly cautious.
![Ky -](https://i.stack.imgur.com/4pzzK.jpg?s=256&g=1)
Ky -
Any pronouns. Really, as long as you're respectful, use any singular third-person pronouns to refer to me. More about me on my site! https://KyLeggiero.me Starting on 2016-11-21 and going forward in perpetuity, all content I post on a website in the StackExchange network is written specially for that post, and is licensed under BH-0-PD unless otherwise stated.
Updated on June 01, 2022Comments
-
Ky - about 2 years
I found myself checking for this and asking if it's necessary. I have code like this:
public Object myMethod(Object... many) { if (many == null || many.length == 0) return this; for (Object one : many) doSomethingWith(one); return that; }
But then I wondered... Am I being too cautious? Do I have to check if
many == null
? Is that ever possible in any current Java version? If so, how? If not, I'll probably keep checking, just for futureproofing in case Oracle decides it can be null one day.