Why my method does not see the null object

I don’t seem 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 printed on the console. Why does myMethod not see the passed obj parameter as null.

+7
java
source share
4 answers

The variable "varargs" is introduced in the signature of the Object... objArr method. Each argument passed when calling such a method gets its own slot in the array of this name.

Therefore, when you pass one null , you get an objArr array of length 1, the only element of which is null . The array itself is not NULL; this element matters.

JLS, section 8.4.1 calls these "arity variable parameters":

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

and

Arity method method calls may contain more relevant arguments than formal parameters. All actual arguments of the expression that do not match the formal parameters preceding the parameter of the arity variable will be evaluated and the results stored in an array that will be passed to the method call (§15.12.4.2).

(my accent)

+13
source share

A method with a list of parameters such as Object... objArr takes an array parameter. When you call it from main , this parameter is an array with one element. One objArr[0] element 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 is still non-zero. This will be an array of length 0.

+6
source share

The objArr array objArr not be empty if you call this function, pass one obj argument from main . obj is null, but the array contains this null element, which means the array is 1 in size and not null.

0
source share
 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"); } 

EXIT →

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

objArr behaves like args basically (String [] args ) and if u tries objArr [1], it throws an exception meaning that objArr is almost an array

0
source share

All Articles