Check whether a string is not null and not empty

后端 未结 30 2098
予麋鹿
予麋鹿 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:59

    Simply, to ignore white space as well:

    if (str == null || str.trim().length() == 0) {
        // str is empty
    } else {
        // str is not empty
    }
    
    0 讨论(0)
  • 2020-11-22 03:00

    Use org.apache.commons.lang.StringUtils

    I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:

    import org.apache.commons.lang.StringUtils;
    
    if (StringUtils.isNotBlank(str)) {
        ...
    } 
    
    if (StringUtils.isBlank(str)) {
        ...
    } 
    
    0 讨论(0)
  • There is a new method in java-11: String#isBlank

    Returns true if the string is empty or contains only white space codepoints, otherwise false.

    jshell> "".isBlank()
    $7 ==> true
    
    jshell> " ".isBlank()
    $8 ==> true
    
    jshell> " ! ".isBlank()
    $9 ==> false
    

    This could be combined with Optional to check if string is null or empty

    boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
    

    String#isBlank

    0 讨论(0)
  • 2020-11-22 03:00

    test equals with an empty string and null in the same conditional:

    if(!"".equals(str) && str != null) {
        // do stuff.
    }
    

    Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.

    the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.

    Also check this answer: https://stackoverflow.com/a/531825/1532705

    0 讨论(0)
  • 2020-11-22 03:01

    You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.

     String str1 = "";
     String str2 = null;
    
     if(StringUtils.isEmpty(str)){
         System.out.println("str1 is null or empty");
     }
    
     if(StringUtils.isEmpty(str2)){
         System.out.println("str2 is null or empty");
     }
    

    will result in

    str1 is null or empty

    str2 is null or empty

    0 讨论(0)
  • 2020-11-22 03:03

    The better way to handle null in the string is,

    str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
    

    In short,

    str.length()>0 && !str.equalsIgnoreCase("null")
    
    0 讨论(0)
提交回复
热议问题