r/java • • Feb 17 '26

Objects.requireNonNullElse

I must have been living in a cave. I just discovered that this exists.
I can code

City city = Objects.requireNonNullElse(form.getCity(), defaultCity);

... instead of:

City city = form.getCity();

if(city == null){

city = defaultCity;

}

113 Upvotes

136 comments sorted by

View all comments

Show parent comment

36

u/vowelqueue Feb 17 '26

Subtle difference: in your code, city might end up being null if both form.getCity() and defaultCity are null.

requireNonNullElse will throw an exception in this case. If it returns, it will always give you a non-null value.