What are the different ways to check for null in Java?
There are several ways to check for null in Java.
- Use conditional statements for evaluation:
if (object == null) {
// 对象为null时的处理逻辑
}
- Make a judgement using the ternary operator.
result = (object == null) ? "null" : "not null";
- Evaluate with the isNull method from the Objects class (Java 7 and above versions).
if (Objects.isNull(object)) {
// 对象为null时的处理逻辑
}
- Use the nonNull method of the Objects class for validation (Java 7 and above).
if (Objects.nonNull(object)) {
// 对象不为null时的处理逻辑
}
- Check with the isPresent method of the Optional class (Java 8 and above):
Optional<Object> optional = Optional.ofNullable(object);
if (optional.isPresent()) {
// 对象不为null时的处理逻辑
}
- Check with the ifPresent method of the Optional class (Java 8 and higher):
Optional<Object> optional = Optional.ofNullable(object);
optional.ifPresent(value -> {
// 对象不为null时的处理逻辑
});
The above are several commonly used methods for null checking, the specific method to use will depend on the actual requirements and coding style.