I've recently reviewed code twice, from two different authors, where the author has cleverly used Thingy z = Optional.ofNullable(x).orElse(y) rather than using, say, Thingy z = x == null ? y : x.

My first reaction was that this is not the intended use or semantic of Optional and that a ternary conditional operator, or even just an if-else, would be better.

But the more I look at it, there is a beauty and a fluidity to Thingy z = Optional.ofNullable(x).orElse(y) which makes sense. To be honest, I've actually never loved the conditional operator.



1 Answer 1


I consider it more as a preference or inclination for Java features.

I mean, calling ofNullable has a time and space cost (passing params by copy + internal execution) same as orElse, it is a bit more than the ternary, secondly, the ternary is qute compact and if in some sense harder to read than Optional... it is clear which is your intent.

Trying to be objective (if possible)

  • Optional is in general more readable (not all of us are familiar with the ternary)
  • It depends on your likes
  • If efficiency is needed, well I consider there are better options than Java, and also some integrations with other technologies are also to be taken into account.

I hope it helped you.

  • 4
    \$\begingroup\$ This answer is quite subjective. And no wonder, the OP's question tends to generate opinion based answers. You should avoid making opinion based answers. What more, the OP's question is hypothetical, thus off topic and you should not answer off topic questions at all. \$\endgroup\$
    – slepic
    Sep 1, 2020 at 4:37
  • 2
    \$\begingroup\$ Going along with what @slepic stated, Please refrain from answering questions that are likely to get closed.. Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic. \$\endgroup\$ Sep 1, 2020 at 5:44
  • 3
    \$\begingroup\$ Well it's something that's come up twice in professional code reviews. I have debated it with a colleague and searched the internets. This seems like the best forum to sort out the possibilities. I'm happy to take the question elsewhere. \$\endgroup\$
    – Kirby
    Sep 1, 2020 at 6:41
  • \$\begingroup\$ Protip: stackoverflow is not about earning reputation, but about getting things sorted out. \$\endgroup\$
    – Florian F
    Jan 17, 2023 at 10:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.