r/learnjava • u/edurbs • 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;
}
8
Upvotes
View all comments
Show parent comment
2
u/vegan_antitheist Feb 19 '26
Optional is basically like undefined in JS.
It's just another way to say that there isn't anything.
But since "null" is used as a value, it's still something. When you get an empty optional it's actually "nothing".
But JS also has "empty" for when an array doesn't have any value at some index (not even null or undefined), so Java is not quite there yet.
Someday we will have null, nil, nothing, none, empty, undefined, void, (), [], {}, ∅, and a bunch of other ways do say that there is nothing. And don't forget NaN for when a number is not a number.