Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java varargs be null? [duplicate]

Tags:

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.

like image 409
Ky. Avatar asked Feb 02 '15 04:02

Ky.


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 .

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?

A method with variable length arguments(Varargs) in Java can have zero or multiple arguments.

Is it good to use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.


1 Answers

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.

like image 94
Dave Avatar answered Sep 17 '22 13:09

Dave