1.判断对象是否为null
==或者 Objects.isNull()来判断该对象是否非空。
Student student = new Student();
student.name="jack";
student.age=18;
if(student==null){
//...
}
if (student.name==null){
//...
}
if (Objects.isNull(student)){
//...
}
if(Objects.isNull(student.name)){
//...
}
2.判断字符串是否为空字符串或null
可以用StringUtils中的isEmpty()或者isBlank()判断字符串是否为空或空字符串
isEmpty()只有当字符串为空字符串如:"",才返回true。 ""里面什么都没有,连空格都没有
isBlank()是Java11中引入的。当字符串为空或者仅包含空白字符(如空格、制表符、换行符等)时,isBlank()
方法返回 true
==或者 Objects.isNull()判断字符串是否为null
String demo;
demo=" ";
if(demo.isEmpty()){
System.out.println("empty"); //false
}if(demo.isBlank()){
System.out.println("blank"); //true
}if(demo==null){
System.out.println("null"); //false
}if(Objects.isNull(demo)){
System.out.println("null"); //false
}
3.判断集合是否为空
可以使用 isEmpty()
方法或 Objects.isNull()
方法来判断集合是否为空或为null,也可以使用 CollectionUtils工具类,该包需要引入。 包下的 CollectionUtils.isEmpty()方法。
List<String> list = null;
// 判断集合是否为null或空
if (list == null || list.isEmpty()) {
System.out.println("集合为空或null");
}
// 使用Objects.isNull()方法判断集合是否为null
if (Objects.isNull(list)) {
System.out.println("集合为null");
}
4.判断数组是否为空或null
可以使用数组的长度判断来判断数组是否为空或null。
int[] arr = null;
// 判断数组是否为null或空
if (arr == null || arr.length == 0) {
System.out.println("数组为空或null");
}