If an array is empty, it looks like you can't check it's length using ".length". What's the best way to check if an array is empty?
Arrays in Java use zero-based counting. This means that the first element in an array is at index zero. However, the Java array length does not start counting at zero.
Is there any difference between checking an array's length as a truthy value vs checking that it's > 0? Since the value of arr. length can only be 0 or larger and since 0 is the only number that evaluates to false , there is no difference.
A zero length array is simply an array with nothing in it. It is an advantage to have such an array, especially in Java, so you can return a valid array and guarantee that your length check never fails. In Java, an array even of primitive types (i.e. int[] ) is still an object. It has a length property.
If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.
You can absolutely check an empty array's length. However, if you try to do that on a null reference you'll get an exception. I suspect that's what you're running into. You can cope with both though:
if (array == null || array.Length == 0)
If that isn't the cause, please give a short but complete program demonstrating the problem. If that was the cause, it's worth taking a moment to make sure you understand null references vs "empty" collections/strings/whatever.
Yeah, for safety I would probably do:
if(array == null || array.Length == 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With