Checking for a not null, not blank String in Java

前端 未结 8 1646
猫巷女王i
猫巷女王i 2021-01-31 13:24

I am trying to check if a Java String is not null, not empty and not whitespace.

In my mind, this code should have been quite up for the job.

         


        
8条回答
  •  不知归路
    2021-01-31 14:22

    The purpose of the two standard methods is to distinguish between this two cases:

    org.apache.common.lang.StringUtils.isBlank(" ") (will return true).

    org.apache.common.lang.StringUtils.isEmpty(" ") (will return false).

    Your custom implementation of isEmpty() will return true.


    UPDATE:

    • org.apache.common.lang.StringUtils.isEmpty() is used to find if the String is length 0 or null.

    • org.apache.common.lang.StringUtils.isBlank() takes it a step forward. It not only checks if the String is length 0 or null, but also checks if it is only a whitespace string.

    In your case, you're trimming the String in your isEmpty method. The only difference that can occur now can't occur (the case you gives it " ") because you're trimming it (Removing the trailing whitespace - which is in this case is like removing all spaces).

提交回复
热议问题