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);
}
1

5 Answers 5

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 -

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3
if (myArray == null)

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

else if (myArray.Length < 1)

   System.Console.WriteLine("array is empty");

Comments

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.

Comments

1

I think you can use this:

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

UPDATE

Better solution is this one:

TextUtils.isEmpty(str)

1 Comment

There is no 'isEmpty()' method for string arrays in java.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.