方式一:自己判断
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!
2 引入外部类
Almost every library I know defines a utility class called StringUtils
, StringUtil
or StringHelper
, and they usually include the method you are looking for.
My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the
- (String) and the
- (String) method
(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)
Just adding Android in here:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}