Why does a null string passed when expecting an array returns size of that array as 1?

Sagar Saxena :

I am extremely confused on multiple fronts. Can someone shed some light onto this. Here is a sample code.

public static void main(String[] args) {
    String str = null;
    abc(str);
}
static void abc(String... str){
    System.out.println(str.length);
}

OUTPUT : 1

jbx :

Let's break it down. I renamed the parameter name to make it clearer.

static void abc(String... arrayOfStrings){
    System.out.println(arrayOfStrings.length);
}

The String ... is saying that instead of passing an array, you can pass the items one after the other as arguments and underneath they will be combined into an array for you. You can still pass an explicit object of type String[] (in which case it will not create the array for you), but passing just null assumes it is of type String not String[].

You are doing abc(null) (because the argument you are passing is null).

So arrayOfStrings will have one item, which happens to be a null reference.

So, arrayOfStrings.length returns 1.

If you did abc(null, null), you would get 2.

If you did abc((String[]) null) you would get a NullPointerException because you would be trying to get the length of a null object reference. If you expect to pass nulls, make sure abc() checks for null before accessing the array passed as an argument.

As a general best practice avoid passing null as much as possible, it is better to pass an empty array. Passing null is just a poison pill, waiting for some method to forget to check for null and throwing NullPointerException.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85886&siteId=1
Recommended