What are the different ways to check for null in Java?

There are several ways to check for null in Java.

  1. Use conditional statements for evaluation:
if (object == null) {
    // 对象为null时的处理逻辑
}
  1. Make a judgement using the ternary operator.
result = (object == null) ? "null" : "not null";
  1. Evaluate with the isNull method from the Objects class (Java 7 and above versions).
if (Objects.isNull(object)) {
    // 对象为null时的处理逻辑
}
  1. Use the nonNull method of the Objects class for validation (Java 7 and above).
if (Objects.nonNull(object)) {
    // 对象不为null时的处理逻辑
}
  1. Check with the isPresent method of the Optional class (Java 8 and above):
Optional<Object> optional = Optional.ofNullable(object);
if (optional.isPresent()) {
    // 对象不为null时的处理逻辑
}
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds