举例:
String a = “abc”;
String b = “abc”;
System.out.println(a.equal(b));
true
System.out.println(a == b);
true 字符串是常量,a和b地址一样
String c = new String(“123”);
String d = new String(“123”);
System.out.println(c.equal(d));
true
System.out.println(c == d);
false new出来的会申请不同的地址,c和d地址不一样
结论:不要使用==和!=判断字符串是否相等,要用equals方法。
判断空串时 str != “” 是错误的,应该使用“”.equals(str) 或者 str.length() ==0
字符串不为空指针和不为空串
if(str != null && !"".equals(str))
处理工具:
apache的包
commons-lang3 兼容性更好
commons-lang 兼容性差,比较旧
public class Test1 {
public static void main(String[] args) {
// 判断字符串是否为空
System.out.println(StringUtils.isEmpty(null)); // true
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(" ")); // false
System.out.println(StringUtils.isEmpty("a")); // false
// 判断字符串是否为非空
System.out.println(StringUtils.isNotEmpty(null)); // false
System.out.println(StringUtils.isNotEmpty("")); // false
System.out.println(StringUtils.isNotEmpty(" ")); // true
System.out.println(StringUtils.isNotEmpty("a")); // true
// 判断字符串是否为空或长度为0或者是否是空白符
System.out.println(StringUtils.isBlank(null)); // true
System.out.println(StringUtils.isBlank("")); // true
System.out.println(StringUtils.isBlank(" ")); // true
System.out.println(StringUtils.isBlank("a")); // false
// 判断字符串是否不为空且长度不为0且不是空白串
System.out.println(StringUtils.isNotBlank(null)); // false
System.out.println(StringUtils.isNotBlank("")); // false
System.out.println(StringUtils.isNotBlank(" ")); // false
System.out.println(StringUtils.isNotBlank("a")); // true
}
}
StringUtils.isNotBlank(str)相当于(str != null && !"".equals(str))