Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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;.

like image 366
Martin Thoma Avatar asked Nov 18 '12 20:11

Martin Thoma


1 Answers

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.

like image 69
mishadoff Avatar answered Oct 11 '22 11:10

mishadoff