Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid printing empty array elements?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading