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

8

u/kubelke Feb 17 '26

What until you find out that you can use Objects.equals that supports null

9

u/edurbs Feb 18 '26

thanks, documented ;)

// These would throw NPE if city is null:
city.equals(otherCity);

// Old school workaround:
if (city != null && city.equals(otherCity))

// Clean, null-safe:
Objects.equals(city, otherCity); // returns true if both are null, false if only one is
→ More replies (5)

1

u/rzwitserloot Feb 21 '26

You're likely doing it wrong.

null should not equal null. Objects.equals is bad. SQL gets this better.

null mostly means what you want it to mean, but java itself inherently 'forces' it upon you when you create an array of a reference type (all cells of the array start out as null; inherent in the language, you can work around it with Arrays.fill), and any field that lacks an initializer (or is somehow accessed before that initializer has executed) is null.

But, mostly - it's what you want it to mean.

But here's thing - null is inflexible. It throws an exception no matter what question you ask a null object and you cannot change this.

Hence, there is one, and only one, meaning that null should ever have: The semantic meaning of "it doesn't exist at all - therefore it is silly to even begin to ask the question". If I ask a string how long it is, "" would respond with 0. null should not (and indeed, does not - it 'responds' with an NPE instead). That's correct. Because how long is an unknown string?

The answer is.. unknown. That's sort of the point. NPE is what you want here.

I have 2 strings. For whatever reason you cannot access them currently. For example because whatever service was meant to give them to me hasn't given them to me yet.

Are they equal?

Yes. No. Maybe? I don't know!

Objects.equals says that these 2 unknown concepts are equal. This is, at a fundamental level, wrong. Subtly so perhaps, but wrong.

What's really happening is that you're associating semantic meaning to null itself. This is a bad idea.

The same thing occurs anytime you see this code:

if (x == null || x.isEmpty()) ...

That code is usually a code smell. Because the code was never intended as an actual OR construct. Instead it is semantically confused about how x referring to some specific semantically well defined state (namely: Empty) is actually represented. Empty string? null? I don't remember, fuck it, let's just cover both bases.

This is a bad way to code. And it leads to unexpected NPEs that you then don't like and makes you say delirious things like 'null is a billion dollar invention' or whatever that was.

Objects.requireNonNullElse is not inherently 'wrong' here. That's just a way to convey the idea of: "I want to do an operation on an expression, where that expression is the notion: "If X is initialized, I want X, but if it is not, I want this default value" which is totally reasonable.

Objects.equals is not so lucky. It is semantically confused. "If X and Y are both present, I want to compare them. If one is present but the other is as yet uninitialized, I want to for some bizarre reason conclude that therefore X and Y must not be equal. Except if both are uninitialized; then they ARE equal." This entire concept is hopelessly confused about the difference between a reference itself and the object a reference is referencing.

The fact that you think Objects.equals is highly useful is why you hate null. Because you're using it wrong.

When you do it 'right', null rarely occurs. The classic "If your method returns a list and you want to return the notion that no results have been found, then return an empty list. Do not return null" is one rather trite example of how to 'do it right'.

1

u/kubelke Feb 21 '26

No, I know how it works and there are cases where I want to compare 2 nulls and this is fine

63

u/zattebij Feb 17 '26

final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);

... is still more readable imo, plus you can use orElseGet to avoid getting the defaultCity when it's not required.

11

u/edurbs Feb 17 '26

I think the Optional would be more suitable for use in method return values, as I read in somewhere

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.

49

u/JustADirtyLurker Feb 17 '26

You're wrapping into an optional and immediately unwrapping it. Okeydokey.

64

u/koefteboy Feb 17 '26

I find this less readable. Also, it's a perfect example of Optional abuse.

-3

u/hwaite Feb 17 '26

If this is abuse, what would you consider to be a good use case? It doesn't get much simpler.

31

u/Linvael Feb 17 '26

One thing thats iffy here is that its a bridge between styles. If this was a coherent Optional-using codebase form.getCity() would be returning an Optional, clearly marking to the users that it might not be there - and making the ofNullable() call unnecessary here, making the line cleaner.

→ More replies (2)

9

u/metaquine Feb 18 '26

Gonna hard disagree with that

15

u/Calm_Seaworthiness87 Feb 18 '26

Creates an unnecessary object.

2

u/__konrad Feb 18 '26

Not if getCity is null...

-13

u/[deleted] Feb 18 '26

[removed] — view removed comment

7

u/ForeverAlot Feb 18 '26

An optimization requires you to perform more work to save the computer work. If you perform more work to inflict more work on the computer, you are not optimizing but pessimizing.

→ More replies (3)

4

u/Jaded-Asparagus-2260 Feb 18 '26

Premature pessimization.

28

u/DesignerRaccoon7977 Feb 17 '26

Ugh I wish they added ?: operator. City city = from.getCity() ?: defaultCity

6

u/Dry_Try_6047 Feb 17 '26

Ehh ... from.getCity() != null ? from.getCity() : defaultCity ... I don't find this too bad. Missing elvis operator doesn't bother me day-to-day

2

u/pragmatick Feb 18 '26

It's more helpful when you chain getter calls.

→ More replies (2)

4

u/hwaite Feb 17 '26

Try Kotlin.

8

u/Jaded-Asparagus-2260 Feb 18 '26

I really don't understand the purpose of such comments. Yes, it's better in Kotlin. But Kotlin is a different language and toolchain. Suggesting to change the stack to Kotlin just for very basic syntactic sugar is mental.

→ More replies (1)

-6

u/hiasmee Feb 17 '26

No it is not 😊 for me. The main message of the line "there is a valid city" hide the details of how it becomes to be valid and set the default city if "form" object is created or parsed from user input.

-2

u/PmMeCuteDogsThanks Feb 17 '26

This is how I write it as well. And if `defaultCity` is an expression, use `orElseGet` to avoid executing it unless necessary.

8

u/_INTER_ Feb 17 '26

There's also Objects::requireNonNullElseGet

1

u/metaquine Feb 19 '26

That's the winner

39

u/Evening_Total7882 Feb 17 '26

Probably it’s because I’m used to requireNonNull, but this name always suggests an exception to me. firstNonNull(…,…)?

15

u/ThierryOnRead Feb 17 '26

Maybe getIfNull like in apache commons ? Although I liked his previous name defaultIfEmpty

10

u/xome Feb 17 '26

Well, you will get an exception if the second argument is null. 

4

u/Jaded-Asparagus-2260 Feb 18 '26

Guava actually named it firstNonNull().

8

u/agentoutlier Feb 17 '26

Bonus in that the JIT basically makes it equivalent performance wise.

The only annoying thing about the method is that some null analysis tools do not like when you pass a nullable.. namely checker (you can change the stubs though). whoops I mean the non default fallback one.

1

u/j4ckbauer Feb 18 '26

I wasn't doubting you, but I was curious how you determined this was equivalent in performance. (To me it does 'seem' easily-optimizable)

1

u/agentoutlier Feb 19 '26

I can’t remember if I saw it with JFR or similar profiler or with -XX:+PrintInlining

1

u/j4ckbauer Feb 19 '26

Thanks, something for me to learn more about!

6

u/nicolaiparlog Feb 18 '26

The Objects.requireNonNull... methods are most commonly used in constructors to ensure that no null slips into a field. These fields are most often final and the one-liner works really well with that:

private final City city;

public SomeType(SomeForm form) {
    this.city = Objects.requireNonNullElse(form.getCity(), defaultCity)
}

If a code base uses these methods with some frequency (mine do), I recommend to statically import them.

13

u/yk313 Feb 17 '26

I’ll give you my ternary operator when you pry it from my cold, dead hands.

City city = from.getCity() != null ? from.getCity() : defaultCity;

18

u/Asdas26 Feb 17 '26

I don't like that this forces you to call from.getCity() twice. Java is missing the Elvis operator.

12

u/aoeudhtns Feb 17 '26

really at this point the Objects#requireNonNull family of functions are best for this example. Optional should be reserved mostly to do function chaining.

Here's the choices, basically, besides the ternary.

// needs to create Optional instance
var city = Optional.ofNullable(form.getCity()).orElse(defaultCity);

// no extra wrappers, the impl here is the ternary but re-uses the result from the single call
var city = Objects.requireNonNullOrElse(form.getCity(), defaultCity);

// still no wrappers, but 4 vs 1 line.
var city = switch (form.getCity()) {
  case null -> defaultCity;
  case City c -> c;
};

// trad with enhancements, avoids double-call, still 4 lines
City city = defaultCity;
if (form.getCity() instanceof City c) {
    city = c;
}

// very traditional - and still very readable
City city = form.getCity();
if (city == null) {
    city = defaultCity;
}

4

u/john16384 Feb 18 '26

form.getCity() instanceof City c ? c : defaultCity

→ More replies (1)
→ More replies (4)

1

u/White_C4 Feb 18 '26

Technically Elvis operator is just syntactic sugar so in code, it's the same. But, it's easier to type for sure.

2

u/larsga Feb 18 '26

Typing doesn't matter, but it's much easier to read.

1

u/Yeah-Its-Me-777 Feb 18 '26

Does it actually invoke the "getCity" twice, like in the ternary? Because that is a semantic difference.

On the other hand, if your getCity-Method is not idempotent you have bigger problems :D

2

u/White_C4 Feb 18 '26

So I did more research on this, turns out getCity() is only called once. It converts

City city = from.getCity() ?? defaultCity;

to

City temp = from.getCity();
City city = temp != null ? temp : defaultCity;

I was half right with my original statement.

→ More replies (1)

4

u/noswag15 Feb 18 '26

No one seems to be mentioning the new form that got unlocked with the recent instanceOf improvements

City city = from.getCity() instanceOf City city ? city : defaultCity;

I don't have a preference between this (instanceOf) and the OP's pattern (Objects.requireNonNullElse)

but both of those feel better than repeating from.getCity() twice.

1

u/yk313 Feb 17 '26

Also, if you model getCity to carry the optionality information by returning Optional<City> then that makes it easy for the callers to:

  1. Recognize the value can be optional (without looking elsewhere)
  2. Use nice optional API: getCity().orElse(defaultCity)

1

u/Known_Tackle7357 Feb 18 '26

And then after some time it will become City city = defaultCity; Optional<City> optionalCity = getCity(); If (optionalCity != null & optionalCity.isPresent()) { city = optionalCity.get(); }

Been there

2

u/White_C4 Feb 18 '26

If you need to check if Optional<City> field is not null, you're kind of defeating the point of not having a default value for it. Just set it to Optional.empty() then only do a optionalCity.isPresent() check every time.

1

u/Jaded-Asparagus-2260 Feb 18 '26

@NonNull Optional<City> getCity() {}.

7

u/nlisker Feb 17 '26

SO has a long discussion on this. But yes, it's a known API and I'm surprised when people don't know it.

1

u/Least_Bee4074 Feb 18 '26

I started doing this when another senior colleague would always flag it in my PR and say “don’t let your objects get into an invalid state.”

Now I’m in a project where we’ve adopted this practice and the new engineering manager has come in and ordered us all to remove them claiming it adds to cognitive load. His reasoning is that we can look at all the call sites and confirm that as of now, none will produce nulls. And if in the future we call into something, the dev and the reviewers should know to check that no nulls happen in whatever spots (which sounds very error prone to me).

He also ordered us to remove static imports.

3

u/j4ckbauer Feb 18 '26

Ugh, if your senior is so confident that a thing will never be allowed to happen, the way you'd confirm this is not by having to look at call sites. Does this not increase cognitive load?

I would think this is what usage of @ NonNull with static analysis is for, now you don't need to distract yourself by checking any call sites.

I get the idea of reducing complexity by never allowing something to happen (so it never needs to be checked for), but if the method for avoiding the bad thing is 'everybody try really hard not to make the mistake', I feel that person learned some of the wrong lessons in their career. You don't avoid having bugs by trying really hard not to have bugs....

Curious what others think.

1

u/nlisker Feb 18 '26

The way you phrased it, it sounds suicidal from the project's perspective. "the dev and the reviewers should know to check" is a bad idea. Maybe he meant that nulls should only be checked at the boundary (entry points), and then all the code that is the implementation doesn't need to check nulls again.

For example:

public int sumTrace(Matrix m1, Matrix m2) {
    // require non-null check here
    int trace1 = tr(m1);
    int trace2 = tr(m1);
    return trace1 + trace2;
}

private int tr(Matrix m) {
    // no need to check null since the input was sanitized
    // ...
}

Static imports can cause readability issues because it's not clear where the method comes from. There are some cases, like the Collectors class where it's not too ambiguous.

1

u/BeyondFun4604 Feb 18 '26

Which java version were you using

14

u/narrow-adventure Feb 17 '26 edited Feb 18 '26

I personally think that Java is getting worse not better with each of these additions.

If != null is perfectly readable and clear :/ I find myself liking Go more and more each time I see these simplifications that are overly verbose for no reason… but maybe I’m just getting old…

Edit: Thank you everyone for commenting, I've enjoyed reading different perspectives and I really tried to clarify my thoughts and reply to everyone.

7

u/BeautifulTaeng Feb 17 '26

I also think they're ugly, but they force developers to handle nulls properly. Verbosity > having to deal with a NPE on production.

0

u/narrow-adventure Feb 17 '26

But he’s not even using Optional at all, with this he can still end up with NPE, no?

4

u/Ignisami Feb 17 '26 edited Feb 17 '26

imo using Optional to dodge nullities like this is kind of abusing it. It's goated for streams and the like, not to dodge != null checks.
In this specific example Optional.ofNullable(form.getCity()).orElse(defaultCity) can still result in an Optional of null (in case defaultCity is also null somehow). In which case you're still fucked. Unwrapping an Optional.ofNullable(null) does give you null and if you use that with the expectation of not having to deal with NPE you're gonna unwrap the Optional and get bodied.

(edit: and using Optional.of(form.getCity()).orElse(defaultCity) instantly throws an NPE and does not proceed to the orElse if form.getCity() is null.)

Meanwhile, Objects.requireNonNullElse(form.getCity(), defaultCity) will throw an NPE if both form.getCity() and defaultCity are null. Fails fast, fails where you'd expect something like this to fail. Very nice.

→ More replies (1)

5

u/ryan_the_leach Feb 18 '26

It's the length of method name tbh.

If it was in the language since day 1, everyone would be static importing def(nullable, defaultValue) and not debating about readability because "of course everyone knows the default value function"

You can debate about the readability to people outside the skill niche, or how accessible it is for newcomers, but Objects.requireBlahBlah is just too much visual noise for something so simple.

4

u/narrow-adventure Feb 18 '26

I agree, I think that verbosity has totally increased.

On top of the new functions being quite lengthy, I think that people chaining too many stream/optional functions makes it really hard to read code. Like 3-4 short chains is fine, but if it goes up to 10 it just becomes unreadable for me.

13

u/IncredibleReferencer Feb 17 '26

I've been knee deep in a modern java project lately and I feel the opposite. I love almost all the changes in modern java. To each their own.

3

u/narrow-adventure Feb 17 '26

It’s not the type of code I like reading in general, might be preference based. I thought we peaked ~2015 w Java 8, everything after that has been downhill for me :/ except for virtual threads - those are epic.

17

u/account312 Feb 17 '26

But switch is like 1000x better in 25 than in 8.

→ More replies (15)

2

u/Ifeee001 Feb 18 '26

I'm confused. The objects class has been around for quite a while now. Java 7 I think? Which additions are you talking about?

1

u/narrow-adventure Feb 18 '26

Hmm so for example the function from the comment requireNonNullElse, I just googled it and it looks like it’s been added in 2017 Java 9, did it really need to be, if people wanted it couldn’t they have just included a library?

I feel like after Java 8 the release cadence has sped up drastically leading to a ton of standard library expansions/features being included into the language that should not have been included. There are way too many ways to get things done and I think that over time it will lead to code quality drops (due to devs misunderstanding the code/language features).

I’ll do another hot take: If Java keeps adding features at this pace it will eventually become another scala.

Got the hot take in now we wait for the dislikes haha

4

u/Ifeee001 Feb 18 '26

Part of what makes a language nice is not having to use a library for every little thing. Something as simply as using a default value should not have to be disconnected from the standard library. Yes, it's as easy as editing a config file or running a command, but it's still not connected to the regular user experience.

Languages evolve. The popular and default way to do somethings in 2008 SHOULD be different from how it's done in 2026 because if it's not, then that means absolutely no progress has been made throughout that time.

Saying something that makes no sense doesn't necessarily make it a hot take.

1

u/narrow-adventure Feb 18 '26

Interesting, we don’t disagree about languages evolving, I think well thought out features that simplify development are great. I just don’t think this is it, I think we’re adding a lot of bloat to the language. I could be wrong and the next 10-15 years will definitely prove it one way or the other.

The ‘hot take’ was a joke, but which parts of it do you find nonsensical? I was trying to make a parallel (and maybe poorly) between scala a crazy feature packed language in 2016 and it’s trajectory (downwards) and Javas future trajectory if it keeps adding things at this pace. But if you have genuine thoughts about this I’m all ears, like do you think it’s not changing too fast?

2

u/White_C4 Feb 18 '26

Yeah, the need to do one liners is the opposite of being clear, it creates more abstractions and leads to debugging being a bit of a hassle to deal with.

4

u/kiteboarderni Feb 17 '26

Old man shouts at clouds...this api has been available since 2017. Almost 10 years ago.

0

u/narrow-adventure Feb 17 '26

Gosh darn kids and their modern 10yo APIs lol

1

u/Away_Advisor3460 Feb 17 '26

IMO the main advantage of optionals is for legacy code where you need to convey the possibility of a null value occurring from some weird-ass legacy function, because time constraints prevent you properly rooting into why, preventing that null and adding proper test coverage.

1

u/narrow-adventure Feb 17 '26

Agreed, he’s not using optional tho..

0

u/[deleted] Feb 17 '26

[deleted] — view deleted comment

10

u/ba0lian Feb 17 '26

So refreshing to hear it, thank you. I swear these must be the same people that compare languages by how short you can make Hello World.

3

u/Sacaldur Feb 18 '26

Did you know that this concludes that the HQ9+ family of programming languages is the absolute best? A Hello World only requires a single character!

(/s just in case)

1

u/ba0lian Feb 18 '26

Never heard of it before, hilarious!

1

u/Sacaldur Feb 18 '26

I said "family" for a reason. There are also HQ9++ which extends the language with object oriented concepts, and HQ9+- which adds exceptions. Very fascinating languages!

While I have your attention, did you ever come across the programming language Whitespace?

1

u/john16384 Feb 18 '26

It's not so much the one liner aspect, but the single assignment aspect as a reason to do this. Using a multiline switch expression or ternary spread over multiple lines is also good (only a single assignment).

4

u/hiasmee Feb 17 '26

Suggestion: Why not do it where form is created?

2

u/strat-run Feb 20 '26

My how did I go so long without this feature was the Optional class. So many null pointer checks and exceptions could have been avoided.

2

u/witness_smile Feb 22 '26

You can even use Optionals and write

String city = Optional.ofNullable(form.getCity())
    .orElse(defaultCity);

And you can even chain it, say the city is in a nested object like Form -> Address -> City

String city = Optional.ofNullable(form)
    .map(Form::getAddress)
    .map(Address::getCity)
    .orElse(defaultCity)

And when any part of the Optional chain is null, it will short circuit to the default value

1

u/BordicChernomyrdin Feb 18 '26

Same here! I just used this for the first time last week!

1

u/nekokattt Feb 18 '26

i like requireNonNullElseGet

1

u/red_dit_nou Feb 20 '26

Two words: Ternary Operator

0

u/White_C4 Feb 18 '26

I don't really understand the need to make it into one line. You're adding more unneeded abstraction. If you decide later you need to add more checks if city is null, well you have to go back to the traditional way.

Readability wise, the bottom one is better. Performance wise, the bottom one is still faster (I know for this case the difference is negligible but point still stands). Code adaptability wise, the bottom is more flexible.

4

u/christoforosl08 Feb 18 '26

I think the point is … less code. Less dose the better

0

u/White_C4 Feb 18 '26

Less code? You mean more abstraction which was my original point. More abstraction isn't necessarily a good thing.

-4

u/Gnerglor Feb 18 '26

Or you could just upgrade to Kotlin.

0

u/[deleted] Feb 18 '26

[deleted] — view deleted comment

2

u/ryan_the_leach Feb 18 '26

Which shows why operators for this are appreciated so much by the c# community.

1

u/[deleted] Feb 18 '26

[removed] — view removed comment

2

u/nekokattt Feb 18 '26

you can put a breakpoint on this though..? it isnt a special construct.

-1

u/[deleted] Feb 19 '26

[removed] — view removed comment

2

u/vips7L Feb 19 '26

I don’t really think you know what functional programming is. 

1

u/nekokattt Feb 19 '26

if you are debugging the behaviour of the JDK itself rather than just looking at what it returns, that feels like you don't really understand what you are trying to debug

0

u/[deleted] Feb 18 '26

[deleted] — view deleted comment

1

u/dstutz Feb 18 '26

I am by no means a FP connoisseur, but I do use a sprinkling and I think of the biggest values is that FP functions are supposed to be "pure" meaning the same inputs will yield the same outputs. These types of functions are easier to test and require less/no mocking. I've seen some people suggest a good application architecture is "functional core, imperative shell" (eg: https://testing.googleblog.com/2025/10/simplify-your-code-functional-core.html).

1

u/OwnBreakfast1114 Feb 19 '26

This is such a weird take, that I'd be curious to hear how you even define functional programming.