Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does passing null to varargs give length 1?

I've been using Java's variable arguments in my methods, and have been testing them by passing in null as a parameter:

public void method(Object A, Object...b) {
    if(A == null || b == null || b.length == 0) return;
...(something that invokes b)...

public void test() {
    method(new Object(), null)
...

At the beginning of the method, I checked for null as the parameter, and even for the length to be 0. But since the test kept failing because of a NullPointerException, I ran the debugger, and b was length 1! It even said when I clicked on the disclosure triangle for b,

all elements are null

I eventually resolved this by checking for length 1 and element 0 is null, but does anyone have an explanation for why Java does this? Thanks!

like image 913
Jeeter Avatar asked Nov 27 '22 20:11

Jeeter


2 Answers

Because you're passing in a value of null.

If you want your varargs method to receive an empty array, either

  1. pass that explicitly:

    method(new Object(), new Object[0])
    
  2. don't pass anything at all:

    method(new Object())
    

Option 2 would be more idiomatic.

like image 179
Armand Avatar answered Dec 15 '22 03:12

Armand


null is a value.

You provide a single value for the varargs argument, so the array will be new Object[] { null } which has a length of 1.

If you wanted to pass no values at all, you'd have to call method(new Object());.

like image 41
Joachim Sauer Avatar answered Dec 15 '22 05:12

Joachim Sauer