Errors Beginner

Get a non-null value with a clear default, no ternary needed.

โœ• Java 8
String name = input != null
    ? input
    : "default";
// easy to get the order wrong
โœ“ Java 9+
String name = Objects
    .requireNonNullElse(
        input, "default"
    );
See a problem with this code? Let us know.
๐Ÿ“–

Clear intent

Method name describes exactly what it does.

๐Ÿ›ก๏ธ

Null-safe default

The default value is also checked for null.

๐Ÿ“

Readable

Better than ternary for simple null-or-default logic.

Old Approach
Ternary Null Check
Modern Approach
requireNonNullElse()
Since JDK
9
Difficulty
Beginner
Objects.requireNonNullElse()
Available

Widely available since JDK 9 (Sept 2017)

requireNonNullElse returns the first argument if non-null, otherwise the second. The default itself cannot be null โ€” it throws NPE if both are null, catching bugs early.

Share ๐• ๐Ÿฆ‹ in โฌก