-7

I know how to do this for numeric datatypes but please tell my for string arrays.

Say I have a string array of 10 elements in java. Some elements contain words but others contain NOTHING.

How do I run a for loop which prints only the non empty elements?

11
  • 2
    What have you tried so far?
    – Julia
    May 19, 2022 at 15:34
  • I tried if(!(x[i].equals(""))) and if(!(x[i].equals(null))) but ran into java.lang.NullPointerException
    – G.S.
    May 19, 2022 at 15:34
  • How did you do it for "numeric datatypes", and why doesn't that work here? May 19, 2022 at 15:35
  • @scottHunter for numeric datatypes I do if((x[i]!=null){print..} and it works
    – G.S.
    May 19, 2022 at 15:36
  • 1
    x[i].equals(null) is never going to be true May 19, 2022 at 15:37

1 Answer 1

0

To print empty elements:

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == null || arr[i].trim().isEmpty()) {
       System.out.println("Element " + i " + " is null or empty.");
    }
}

The print non-empty elements:

for (int i = 0; i < arr.length; i++) {
    if ( arr[i] != null && !arr[i].trim().isEmpty())) {
       System.out.println(arr[i]);
    }
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.