[Java] How to check if given array is empty?
I want to check if the given array is empty, how to do that in Java?
1 Answer
4 years ago by Eleven
We need to check if the value is not null and the length is greater than zero to make sure array is not empty. Following code shows how to do that
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "red", "green", "blue", "orange", "maroon" };
String[] emptyArray = {};
String[] nullArray = null;
System.out.println(isArrayEmpty(colors));
System.out.println(isArrayEmpty(emptyArray));
System.out.println(isArrayEmpty(nullArray));
}
static boolean isArrayEmpty(String[] inp) {
return (inp != null && inp.length > 0) ? true : false;
}
}
Output
true
false
false
You can check the code online here: https://onecompiler.com/java/3xmt736jt
4 years ago by Karthik Divi