Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Does Java have null-coalescing operator?

At the time of this writing, Java does not provide a null coalescing operator. Fortunately, we can approximate the behavior by using Optional .

Does Java have Elvis operator?

Java has no Elvis operator (or null coalescing operator / null-safe member selection) but with lambda expressions / method references you can roll your own.

What is coalesce in C?

The COALESCE expression allows for user-specified NULL-handling. It is often used to fill in missing values in dirty data. It has a function-like syntax, but can take unlimited arguments, for example: COALESCE(a, b, c, x, y, z) .

What is nullable types and null-coalescing operator in C#?

Nullable types work as a connector between a database and C# code to provide a way to transform the nulls to be used in C# code. Null Coalescing operators simplify the way to check for nulls and shorten the C# code when the developer is dealing with nulls.


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.


Guava has a method that does something similar called MoreObjects.firstNonNull(T,T).

Integer x = ...
int y = MoreObjects.firstNonNull(x, -1);

This is more helpful when you have something like

int y = firstNonNull(calculateNullableValue(), -1);

since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.


Short answer: no

The best you can do is to create a static utility method (so that it can be imported using import static syntax)

public static <T> T coalesce(T one, T two)
{
    return one != null ? one : two;
}

The above is equivalent to Guava's method firstNonNull by @ColinD, but that can be extended more in general

public static <T> T coalesce(T... params)
{
    for (T param : params)
        if (param != null)
            return param;
    return null;
}

No, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null.


ObjectUtils.firstNonNull(T...), from Apache Commons Lang 3 is another option. I prefer this becuase unlike Guava, this method does not throw an Exception. It will simply return null;