- You can check if a variable is null using an if statement, for example:
if (variable == null) {
}
- In Java 7 and later versions, you can use the isNull method from the Objects class to check for null values.
if (Objects.isNull(variable)) {
}
- Utilizing Optional class: The Optional class, introduced in Java 8, provides a more convenient way to handle values that may be null, such as:
Optional<String> opt = Optional.ofNullable(variable);
if (opt.isPresent()) {
}
- You can use a ternary expression to check if a variable is null, for example:
String result = (variable != null) ? variable : "default";
- One option:
By using the Objects.requireNonNull method, you can ensure that a variable is not null, for example:
Objects.requireNonNull(variable, "变量不能为null");