Question

I want to know the best practice for checking whether a string array is empty or not.

String[] name = {"a" , "b"};

if (name == null) {
}

Is this a good practice or there are more best codes for the same?

Was it helpful?

Solution 3

To check if a string array is empty...

public boolean isEmptyStringArray(String [] array){
 for(int i=0; i<array.length; i++){ 
  if(array[i]!=null){
   return false;
  }
  }
  return true;
}

OTHER TIPS

Normally you would want to do something like:

if (arr != null && arr.length > 0) { ... }

for non-empty array.

However, as you may suspect, someone have made utils for such kind of common action. For example, in Commons-lang, you can do something like:

if (ArrayUtils.isEmpty(arr)) {... }

if you do a static import for ArrayUtils.isEmpty, this line can be even shorter and looks nicer:

if (isEmpty(arr)) { ... }
if(name!=null && name.length > 0) {
   // This means there are some elements inside name array.
} else {
   // There are no elements inside it.
}

All arrays in Java have a special field "length" that contains the number of elements in the array, that is array length in other words.

String test( String[] array )
{
    if ( array == null ) {
        return "array is null";
    }
    if ( array.length == 0 ) {
        return "array is empty, meaning it has no element";
    }
    for ( String s : array ) {
        if (s == null) {
            return "array contains null element";
        }
        if (s.length() == 0) {
            return "array contains empty string";
        }
        // or
        if (s.isEmpty()) {
            return "array contains empty string";
        }
    }

    return "array is not null or empty and does not contain null or empty strings";
}

To test whether the array contains a null element or an empty string you need to iterate through it and check each element individually.

Do not forget that the length of array is the special field array.legnth and the length of the string is the function string.length().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top