Objects Null Safe Defaults requireNonNullElse
Give nullable values explicit fallbacks with requireNonNullElse, requireNonNullElseGet, and Objects.toString so the default is stated at the call site.
Code
import java.util.List;
import java.util.Objects;
public class NullSafeDefaults {
public static void main(String[] args) {
String missing = null;
// requireNonNullElse:null 就用默认值;两个参数都为 null 会抛异常
String name = Objects.requireNonNullElse(missing, "guest");
System.out.println("name: " + name);
// requireNonNullElseGet:默认值惰性求值,昂贵构造只在需要时发生
String email = Objects.requireNonNullElseGet(missing, () -> "[email protected]");
System.out.println("email: " + email);
// Objects.toString(obj, default):null 渲染成占位符
System.out.println("label: " + Objects.toString(missing, "(none)"));
// nonNull:方法引用风格的判空过滤
List<String> emails = List.of("[email protected]", null, "[email protected]");
System.out.println("kept: " + emails.stream().filter(Objects::nonNull).count());
// equals:null 安全的两参数比较,不抛 NullPointerException
System.out.println("both null equal: " + Objects.equals(null, null));
System.out.println("value vs null: " + Objects.equals("v1", null));
}
}Inside the snippet
Objects Null Safe Defaults requireNonNullElse keeps everything in the class NullSafeDefaults and the function main.
Data flows through a stream pipeline where each stage returns a new view rather than mutating.
Putting it to use
The run emits 6 labeled sections — name:, email:, label:, kept:, both null equal:, value vs null: — one per step.
Core lines
String email = Objects.requireNonNullElseGet(missing, () -> "[email protected]");
List<String> emails = List.of("[email protected]", null, "[email protected]");
String name = Objects.requireNonNullElse(missing, "guest");
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
FAQ
- What does Objects Null Safe Defaults requireNonNullElse print when run?
- Running the file directly is enough — expect labeled output lines such as `name:`, `email:`, `label:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.