Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the string array is empty or null android? [duplicate]

Tags:

java

android

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);
}
like image 646
hanif s Avatar asked May 30 '13 06:05

hanif s


People also ask

How do I check if a string array is empty or null?

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.

How check array is empty or not in android?

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].

How do I check if a string array is empty?

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.

How check string is null or not in android?

Use TextUtils. isEmpty( someString ) The documentation states that both null and zero length are checked for.


1 Answers

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

like image 63
Ronak Mehta Avatar answered Oct 16 '22 08:10

Ronak Mehta