Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my method not seeing null Object

Tags:

java

I seem not to understand this.

public class NewClass {
    public static void main(String[] args) {
        Object obj = null;
        myMethod(obj);
    }

    public static void myMethod(Object... objArr) {
        if(objArr != null) {
            System.out.println("I am not null");
        }
    }
}

To my surprise, I am not null is printed on the console. Why is myMethod not seeing the passed obj parameter as null.

like image 634
Uchenna Nwanyanwu Avatar asked Oct 02 '13 18:10

Uchenna Nwanyanwu


2 Answers

The method signature Object... objArr introduces a "varargs" variable. Every argument passed in a call to such a method is given its own slot in an array of that name.

Therefore, when you pass one null, you get an array objArr of length 1, whose only element is null. The array itself isn't null, the element is.

The JLS, Section 8.4.1 calls these "variable arity parameters":

The last formal parameter of a method or constructor is special: it may be a variable arity parameter, indicated by an ellipsis following the type.

and

Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).

(emphasis mine)

like image 88
rgettman Avatar answered Sep 19 '22 11:09

rgettman


A method with a parameter list like Object... objArr takes an array parameter. When you call it from main, the parameter is an array with one element. The one element, objArr[0], will be null. But the array itself is not null.

In fact, even if you call the method with no arguments, i.e. myMethod(), the array still isn't null. It will be an array of length 0.

like image 28
ajb Avatar answered Sep 20 '22 11:09

ajb