The ?? operator returns the left-hand argument if the left-hand argument isn’t null. Otherwise, it returns the right-hand argument. Similar to the safe navigation operator (?.), the null coalescing operator (??) replaces verbose and explicit checks for null references in code.
The null coalescing operator is a binary operator in the form a ?? b that returns a if a isn’t null, and otherwise returns b. The operator is left-associative. The left-hand operand is evaluated only one time. The right-hand operand is only evaluated if the left-hand operand is null.
You must ensure type compatibility between the operands. For example, in the expression: objectZ result = objectA ?? objectB, both objectA and objectB must be instances of objectZ to avoid a compile-time error.
Here’s a comparison that illustrates the operator usage. Before the Null Coalescing Operator, you used:
Integer notNullReturnValue = (anInteger != null) ? anInteger : 100;
test
testing