2

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

3
  • Dusting compile time the method call gets translated into new String[]{null} I am assuming. Commented Aug 10, 2018 at 6:59
  • @TA The aim here is to pass a null reference to a method call expecting an Array. Commented Aug 10, 2018 at 7:08
  • 1
    @SagarSaxena if you want to pass a null reference do not use variable arguments. (As a side note, if possible avoid passing null values, its better to pass an empty array... you just risk null pointer exceptions if you forget to do a null check somewhere inside) Commented Aug 10, 2018 at 7:23

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That explains it. Thanks.
Sidenote: using abc((String[]) null) will throw an exception. Because then no additional array will be created
@Lino True, added an explanation for when an object explicitly typed String[] is passed.
"So arrayOfStrings will have one object, of type String which happens to be a null reference" null can't be of String type and array of string does not contain any objects.
Fixed the wording. However null is contravariant with all Object types, including String.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.