一、字符串状态
String字符串的4种状态
- 声明了并别引用值为 null
- 分配了内存空间赋值为 “”
- 分配了内存空间没赋值(默认‘’‘’) String A=new String();
- 只声明了没引用 String B;
- 有值
String空字符串的2种状态
- null
- “”
二、比较字符串为空4种方法
- if(s == null || s.isEmpty())
Java SE 6.0 后开始提供的方法
- if(s == null || s.length() <= 0)
比较字符串长度, 效率最高
- if (s == null || s == “”)
比较直观,简便的方法
- if(s == null ||"".equals(s))
效率很低(== 引用数据类型比较的是值 equals比较的是地址但string类重写了equals方法 比较的是值)
三、StringUtils比较
工具StringUtils的判断方法:
一种是org.apache.commons.lang包下的; 只能比较字符串长度是否为0
public boolean isEmpty() {
return value.length == 0;
}
一种是org.springframework.util包下的:参数是Object类 可以比较任何类型
public static boolean isEmpty(Object str) {
return (str == null || "".equals(str));
}
所以我们一般用springframework包下的stringutil更方便或者直接 if(s == null || s.isEmpty()) 这么比较比较严谨
四、isEmpty() 使用注意
- if(s == null || s.isEmpty())
org.apache.commons.lang包下
使用isEmpty必须在前面先判断是否为空 isnull
isEmpty只是比较字符串是否为空 如果字符串为null 那么会报空指针.NullPointerException
public class text {
public static void main(String[] args) {
String a=null;
System.out.println(a.isEmpty());
}
}