Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between new type[0] and null - java

Tags:

java

arrays

null

What is the difference between

type[] a = new type[0];

and

type[] a = null;

Do either forms occupy any memory ? Are there any similarities / differences ?

like image 283
Codi Avatar asked Jun 24 '15 09:06

Codi


1 Answers

The first one (new type[0]) will actually create an array object (and therefore occupy memory). You can use the (0-sized) array object, for example to get its length or iterate over it, but you can, of course, not access any of its elements. So you can pass it to any function that doesn't make assumptions about the array's length (but does the proper checks instead) and it will work.

The second one (null) doesn't create any object. You will get an exception, if you try to access any member.

like image 188
mastov Avatar answered Sep 27 '22 01:09

mastov