Uchenna Nwanyanwu
Uchenna Nwanyanwu

Reputation: 3204

Why is my method not seeing null Object

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.

Upvotes: 7

Views: 256

Answers (4)

Srinath Ganesh
Srinath Ganesh

Reputation: 2558

if(objArr != null)
        {
            System.out.println("I am not null because I am an ARRAY object");
            System.out.println("I have " + objArr.length + " element(s)");
        }

        if(objArr[0] == null)
        {
            System.out.println("NULL");
        }

OUTPUT ->

  I am not null because I am an ARRAY object
  I have 1 element(s)
  NULL

objArr behaves like args in main(String[] args) and if u try objArr[1] it will throw an exception meaning objArr is almost an array

Upvotes: 0

rgettman
rgettman

Reputation: 178263

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)

Upvotes: 13

Nikhil
Nikhil

Reputation: 2308

The array objArr will not be null, be you are passing one argument obj from main when calling this function. obj is null, but the array contains this null element, which means the array has a size of 1, and is not null.

Upvotes: 0

ajb
ajb

Reputation: 31699

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.

Upvotes: 6

Related Questions