javac#equivalentnull-coalescing-operator

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


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

int y = x ?? -1;

More about ??


Solution

  • 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.