Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty check with String[] array [duplicate]

Tags:

java

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?

like image 955
Piolo Opaw Avatar asked Mar 04 '14 03:03

Piolo Opaw


3 Answers

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)) { ... }
like image 200
Adrian Shum Avatar answered Nov 15 '22 22:11

Adrian Shum


if(name!=null && name.length > 0) {
   // This means there are some elements inside name array.
} else {
   // There are no elements inside it.
}
like image 30
Aditya Avatar answered Nov 15 '22 23:11

Aditya


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;
}
like image 25
Solace Avatar answered Nov 15 '22 23:11

Solace