Sunday, February 15, 2009

When to use an array of size zero ?

Question: Java provides the facility to have an array of size zero. Do we have any scenario when this zero size array can be used ?

Scenario1: Suppose, I have a method returning an array. So the method can return an array with values or null. If the code invoking method is not checking for null, can get an exception.
So sometimes it is better to return an array with size zero to avoid NullPointerException. It could be a good way to return nothing :)

Scenario 2: Think and put a comment please.....


Vivek Athalye said...

just a quick thought..
just like return value, consider a method expecting array as a parameter. if the method doesn't check for null (however "bad practice" it might be) then u can't pass null to it. in that case u'll need to create an empty array and pass it as method argument.

let me think abt more scenarios

Vivek Athalye said...

i think u must have seen this link:

:D :P

u can check following link as well... it gives a well explained example (at the bottom of the page) abt what codingmonkey has mentioned in the above forum.