13

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);
}
user1721904
  • 843
  • 4
  • 13
hanif s
  • 488
  • 1
  • 3
  • 19
  • A better duplicate - [How can I check whether an array is null / empty?](https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null) – Bernhard Barker Sep 12 '17 at 18:20

5 Answers5

43

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 -

Community
  • 1
  • 1
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
9

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

Community
  • 1
  • 1
Ronak Mehta
  • 5,971
  • 5
  • 42
  • 69
3
if (myArray == null)

   System.Console.WriteLine("array is not initialized");

else if (myArray.Length < 1)

   System.Console.WriteLine("array is empty");
Sam
  • 1,124
  • 1
  • 8
  • 12
Vandana
  • 51
  • 2
1
String k[] = new String[3];

if(k.length == 0 ){

System.out.println("Null");
}

it will display null if there is no item in array.

Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
1

I think you can use this:

if(str != null && !str.isEmpty())

UPDATE

Better solution is this one:

TextUtils.isEmpty(str)
Mahdi
  • 6,139
  • 9
  • 57
  • 109