I am new to java. Am unable to check for null. Could you enlighten me on this? I have string array which has no elements.
I tried this code
String[] k = new String[3];
if(k==null){
System.out.println(k.length);
}
To check if an array is null, use equal to operator and check if array is equal to the value null. In the following example, we will initialize an integer array with null. And then use equal to comparison operator in an If Else statement to check if array is null. The array is empty.
k!= null would check array is not null . And StringArray#length>0 would return it is not empty[you can also trim before check length which discard white spaces].
To check if an array contains an empty string, call the includes() method passing it an empty string - includes('') . The includes method returns true if the provided value is contained in the array and false otherwise.
Use TextUtils. isEmpty( someString ) The documentation states that both null and zero length are checked for.
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;
}
}
Reference
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