How to check if a variable is null in Java?
In Java, there are several ways to determine if a variable is empty.
- Determine if a variable is null using an if statement.
String str = null;
if (str == null) {
System.out.println("变量为空");
} else {
System.out.println("变量不为空");
}
- Use the isNull() method of the Objects class to check if a variable is null.
String str = null;
if (Objects.isNull(str)) {
System.out.println("变量为空");
} else {
System.out.println("变量不为空");
}
- Use the isEmpty() method of the StringUtils class to check if a string variable is empty.
String str = "";
if (StringUtils.isEmpty(str)) {
System.out.println("变量为空");
} else {
System.out.println("变量不为空");
}
- Check whether an Optional variable is empty using the isPresent() method of the Optional class.
Optional<String> optional = Optional.ofNullable(null);
if (!optional.isPresent()) {
System.out.println("变量为空");
} else {
System.out.println("变量不为空");
}
These methods can be used to determine whether a variable is empty based on different situations and take appropriate actions accordingly.