28

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Ky -
  • 30,724
  • 51
  • 192
  • 308
  • @sdotdi what would I try? Would `myMethod(null)` not pass it an array like `new Object[]{null}`? – Ky - Feb 02 '15 at 04:40
  • As a side note, the code you have here is a code smell. Passing in a varargs object array means that your method can accept anything. I can imagine specific situations where this might be useful, but I would say that this is generally something to avoid. – Andrew Eisenberg Feb 02 '15 at 04:44
  • 2
    http://ideone.com/wP9AFE – Sotirios Delimanolis Feb 02 '15 at 04:47
  • 2
    As IDEA suggests, `null` can be explicitly passed to varargs methods with cast - `(Object[]) null`, so yes, passing `null` is possible in Java and your check makes sense – RomanMitasov Feb 04 '21 at 09:30

1 Answers1

38

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.

Dave
  • 1,784
  • 2
  • 23
  • 35