Martin Thoma Martin Thoma - 4 months ago 15
Java Question

Why is int[] a = new int[0]; allowed?

Is there a reason why

int[] myArray = new int[0];


compiles?

Is there any use of such an expression?

myArray[0] = 1;


gives
java.lang.ArrayIndexOutOfBoundsException
.

if (myArray == null) {
System.out.println("myArray is null.");
} else {
System.out.println("myArray is not null.");
}


gives
myArray is not null.
.

So I can't see a reason why
int[] myArray = new int[0]
should be preferred over
myArray = null;
.

Answer

It's just for reducing null checks.

You can iterate on empty array but can not iterate on null.

Consider the code:

for (Integer i: myArray) {
   System.out.println(i);
}

On empty array it prints nothing, on null it causes NullPointerException.

Comments