Can we rely on String.isEmpty for checking null condition on a String in Java?

前端 未结 6 2353
南旧
南旧 2020-12-24 10:44

I am passing an accountid as input from an XML file as shown, which will be parsed later and will be used in our code:

123456

        
相关标签:
6条回答
  • 2020-12-24 11:09

    I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);

    From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29

    isBlank
    public static boolean isBlank(String str)
    Checks if a String is whitespace, empty ("") or null.
    
     StringUtils.isBlank(null)      = true
     StringUtils.isBlank("")        = true
     StringUtils.isBlank(" ")       = true
     StringUtils.isBlank("bob")     = false
     StringUtils.isBlank("  bob  ") = false
     
    Parameters:
    str - the String to check, may be null
    Returns:
    true if the String is null, empty or whitespace
    
    0 讨论(0)
  • 2020-12-24 11:10
    String s1=""; // empty string assigned to s1 , s1 has length 0, it holds a value of no length string
    
    String s2=null; // absolutely nothing, it holds no value, you are not assigning any value to s2
    

    so null is not the same as empty.

    hope that helps!!!

    0 讨论(0)
  • 2020-12-24 11:14

    No, the String.isEmpty() method looks as following:

    public boolean isEmpty() {
        return this.value.length == 0;
    }
    

    as you can see it checks the length of the string so you definitely have to check if the string is null before.

    0 讨论(0)
  • 2020-12-24 11:17

    No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.

    Your test should be:

    if (acct != null && !acct.isEmpty())
    

    Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.

    Alternatively, using Guava:

    if (!Strings.isNullOrEmpty(acct))
    
    0 讨论(0)
  • 2020-12-24 11:17

    Use StringUtils.isEmpty instead, it will also check for null.

    Examples are:

     StringUtils.isEmpty(null)      = true
     StringUtils.isEmpty("")        = true
     StringUtils.isEmpty(" ")       = false
     StringUtils.isEmpty("bob")     = false
     StringUtils.isEmpty("  bob  ") = false
    

    See more on official Documentation on String Utils.

    0 讨论(0)
  • 2020-12-24 11:20

    You can't use String.isEmpty() if it is null. Best is to have your own method to check null or empty.

    public static boolean isBlankOrNull(String str) {
        return (str == null || "".equals(str.trim()));
    }
    
    0 讨论(0)
提交回复
热议问题