-3

I need to compare an empty("") String and a Null String and return true.

String a = "";
String b = null;

// return TRUE if I compare "" and null
return TRUE if I compare null and null
return TRUE if I compare "" and ""

return false if a or b has some value

2 Answers2

1

You could use a function to not repeat yourself :

String a = ...;
String b = ...;

Predicate<String> isNullOrEmpty = s -> s == null || s.equals("");
return isNullOrEmpty.test(a) && isNullOrEmpty.test(b);

You can also rely on Apache Command Lang that provides StringUtils.isEmpty() :

return StringUtils.isEmpty(a) && StringUtils.isEmpty(b);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

Your actual usecase is not to compare the strings to each other but instead you want to check if one of both is not empty.

The following snippet should do the job:

public boolean func(String a, String b) {
    if (a != null && !a.isEmpty()) {
        return false;
    }
    if (b != null && !b.isEmpty()) {
        return false;
    }
    return true;
}
wero026
  • 1,187
  • 2
  • 11
  • 23