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

前端 未结 6 2387
南旧
南旧 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: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))
    

提交回复
热议问题