Check whether a string is not null and not empty

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

    str != null && str.length() != 0
    

    alternatively

    str != null && !str.equals("")
    

    or

    str != null && !"".equals(str)
    

    Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

    IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

提交回复
热议问题