pavi
pavi

Reputation: 674

What is the use of Zero length array over null ? can anybody explain with example

I was told to use zerolength arrays instead of nulls in the program.But I couldn't find how to use Zerolength array.Please Help me.

Upvotes: 3

Views: 1317

Answers (4)

blank
blank

Reputation: 18170

Don't pass nulls!

If you pass a zero length array instead of null then a method using it will be able to iterate over it without causing a null pointer exception. The same is true for any collection class

Upvotes: 2

Matt Mills
Matt Mills

Reputation: 8792

A zero length array can be used as an array; you can iterate over its members, for example, or use .length. You can't do that with null because you will get a null reference exception.

Upvotes: 2

Mark Peters
Mark Peters

Reputation: 81074

The idea, in general, is that if a query returns "no results", all things being equal, it is better to return an empty list (or array) than null.

The reason for that is it makes the client code a lot cleaner. You can still do something like this with an empty array:

Account[] accounts = getAccounts();
for ( Account account : accounts ) {
    account.recomputeForInterest();
}

If you tried the same with null you would get a runtime exception. You can create an empty array using a few methods:

Account[] accounts = {};
accounts = new Account[0];
accounts = new Account[]{};

Upvotes: 7

Jon Newmuis
Jon Newmuis

Reputation: 26502

A zero-length array is simply an array with no contents. For example, a zero-length array of int types would be:

int[] myArray = new int[0];

Choosing between null and an empty array is simply a design decision, depending on how you wish to use the code. null requires an extra check (e.g. if (myArray != null) { ... }), but does not actually allocate any space, and therefore may be cheaper if space is of the essence.

Upvotes: 5

Related Questions