There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
Answer from cletus on Stack OverflowThere's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
What i'm trying to do is a program that you need to enter an index and a number so that the number will be filled into that index of an array. So i need to check if an index is already filled, i tried this by filling all the array with zeros but what if the number a i want to insert is a zero? I remember doing this in C by comparing to null but it seems like it doesnt work on java.
I would consider using ArrayUtils.is empty by adding Apache Commons Lang from here http://commons.apache.org/proper/commons-lang/download_lang.cgi
The big advantage is this will null check the array for you in a clean and easily readible way.
You can then do:
if (ArrayUtils.isEmpty(arrayName) {
System.out.printLn("Array empty");
} else {
System.out.printLn("Array not empty");
}
In array class we have a static variable defined "length", which holds the number of elements in array object. You can use that to find the length as:
if(arrayName.length == 0)
System.out.println("array empty");
else
System.out.println("array not empty");