MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o5y1813/?context=3
r/java • u/edurbs • Feb 17 '26
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;
}
136 comments sorted by
View all comments
Show parent comment
36
Subtle difference: in your code, city might end up being null if both form.getCity() and defaultCity are null.
city
form.getCity()
defaultCity
requireNonNullElse will throw an exception in this case. If it returns, it will always give you a non-null value.
requireNonNullElse
View all comments
Show parent comment
36
u/vowelqueue Feb 17 '26
Subtle difference: in your code,
citymight end up being null if bothform.getCity()anddefaultCityare null.requireNonNullElsewill throw an exception in this case. If it returns, it will always give you a non-null value.