1.基本数据类型可以用 == 判断
2.包装类要用equals判断,因为 == 判断的是地址
3.判断是否为空时,将可能为空的值放到前面,防止空指针报错。
String str;
1.str == null
2.str.equals(" ")
说明:
str == null 说明str还未指向一个特定的字符串对象,此时谈不上是否为空。str = “”;说明str是个空字符串,只不过长度为0;
基本上判断对象是否为空,StringUtils.isEmpty(Object str)这个方法都能搞定。
接下来就是判断数组是否为空
list.isEmpty(); //返回boolean类型。
StringUtils类中isEmpty与isBlank的区别
- StringUtils.isEmpty(String str)
System.out.println(StringUtils.isEmpty(null)); //true
System.out.println(StringUtils.isEmpty("")); //true
System.out.println(StringUtils.isEmpty(" ")); //false
System.out.println(StringUtils.isEmpty(“dd”)); //false
- StringUtils.isBlank(String str)
System.out.println(StringUtils.isBlank(null)); //true
System.out.println(StringUtils.isBlank("")); //true
System.out.println(StringUtils.isBlank(" ")); //true
System.out.println(StringUtils.isBlank(“dd”)); //false
empty()与IsEmpty()的比较
empty()与IsEmpty()并没有本质区别。
但是自己又发现在此题中对于字符串s的判断s.empty()会报错,而s.isEmpty不会报错。但是对于栈stack两种均不报错,查看了对于字符串并没有empty()方法。
至此得出的结论为:字符串中只有isEmpty()方法,而栈中两种方法均可以实现。
数组可以:
arr == null