Check whether a string is not null and not empty

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

提交回复
热议问题