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);
}
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);
}
Very precisely
if(k!=null && k.length>0){
System.out.println(k.length);
}else
System.out.println("Array is not initialized or 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].
Some related popular question -
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;
}
}
String k[] = new String[3];
if(k.length == 0 ){
System.out.println("Null");
}
it will display null if there is no item in array.
I think you can use this:
if(str != null && !str.isEmpty())
UPDATE
Better solution is this one:
TextUtils.isEmpty(str)