Skip to content
Advertisement

Checking null for multiple strings in Java

How can one check for whether one of the strings is not null, only if the rest contain something?

Here is an example of how it works, but I feel like there should be a better way to do it.

JavaScript

Is there a way to condense this logic into a better approach?

EDIT

If all strings are null, that’s fine.

If all string aren’t null, also fine.

If at least one is not null and at least one is null, not fine.

SAMPLE

JavaScript

Advertisement

Answer

Based on what I understood of your requirements in the comments this should work.

Count the number of null (or non null, either way works). Then compare that with the amount of strings passed into the method. If the count is neither the length of the list or 0 then it means there is a mix of not null or empty string vs null or empty strings (indicating it’s bad).

JavaScript

Note that count returns long and length method of array will return an int.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement