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

Sagar Saxena
  • 564
  • 5
  • 12
  • Dusting compile time the method call gets translated into `new String[]{null}` I am assuming. – Sagar Saxena Aug 10 '18 at 06:59
  • @TA The aim here is to pass a null reference to a method call expecting an Array. – Sagar Saxena Aug 10 '18 at 07: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) – jbx Aug 10 '18 at 07:23

1 Answers1

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.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • That explains it. Thanks. – Sagar Saxena Aug 10 '18 at 07:09
  • 1
    Sidenote: using `abc((String[]) null)` will throw an exception. Because then no additional array will be created – Lino Aug 10 '18 at 07:10
  • 2
    @Lino True, added an explanation for when an object explicitly typed `String[]` is passed. – jbx Aug 10 '18 at 07:29
  • "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. – GotoFinal Aug 10 '18 at 19:02
  • Fixed the wording. However null is contravariant with all Object types, including String. – jbx Aug 11 '18 at 20:07