Search code examples
javaequalsstring-comparison

Objects.equals() vs StringUtils.isNotBlank() in Java


Could you please explain me if there is a difference between the functionality of the following codes? I know that the Objects.equals() checks for the NULL value first and then compares the two strings.

I have the following conditions and I want to know which one is more practical.

if (StringUtils.isNotBlank(str1) && str1.equals(str2)) {// do sth}

or is it enough to say:

if (Objects.equals(str1,str2)) {// do sth}

Thanks


Solution

  • The Apache Commons method StringUtils.isNotBlank will return false if the string is null, empty, or contains only whitespace. There will be differences in the following situations:

    str1 str2 Results(1st code/2nd code)
    null null false/true
    "" "" false/true
    " " " " false/true