is there a Java equivalent to null coalescing operator (??) in C#?

Nikita Ignatov picture Nikita Ignatov · Mar 7, 2011 · Viewed 90k times · Source

Is it possible to do something similar to the following code in Java

int y = x ?? -1;

More about ??

Answer

Andrzej Doyle picture Andrzej Doyle · Mar 7, 2011

Sadly - no. The closest you can do is:

int y = (x != null) ? x : -1;

Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.