Martin Thoma Martin Thoma - 1 year ago 79
Java Question

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

Is there a reason why

int[] myArray = new int[0];


Is there any use of such an expression?

myArray[0] = 1;


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

myArray is not null.

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

Answer Source

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) {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download