Check whether a string is not null and not empty

后端 未结 30 2428
予麋鹿
予麋鹿 2020-11-22 02:13

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != \"**here I want to check          


        
30条回答
  •  一整个雨季
    2020-11-22 02:45

    To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

    Strings.nullToEmpty(str).isEmpty(); 
    // or
    Strings.isNullOrEmpty(str);
    

    Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).

    Guava's version of Commons Lang isBlank would be:

    Strings.nullToEmpty(str).trim().isEmpty()
    

    I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').

提交回复
热议问题