Explain Codes LogoExplain Codes Logo

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

java
null-coalescing-operator
java-8
best-practices
Alex KataevbyAlex Kataev·Feb 25, 2025
TLDR

Java doesn't have a direct equivalent of C#'s ?? operator. However, you can get a similar functionality using the ternary operator ( ? : ) :

String output = (yourVariable != null) ? yourVariable : "defaultVal";

In the above code, if yourVariable is not null, output will be assigned the value of yourVariable, else output will be assigned "defaultVal".

While not a built-in feature like in C#, Java has several libraries that can bring such functionality to your code. Libraries such as Guava and Apache Commons Lang offer methods to perform a null coalescing operation:

  • Guava:
import com.google.common.base.MoreObjects; // Who you gonna call? Null busters! String output = MoreObjects.firstNonNull(yourVariable, "defaultVal");
  • Apache Commons Lang:
import org.apache.commons.lang3.ObjectUtils; // Null shall not pass! String output = ObjectUtils.firstNonNull(yourVariable, "defaultVal");

Using static utility methods for cleaner code

Another alternative for dealing with potential nulls is to create static utility methods for null-checking. They'll keep your code clean and reduce boilerplate:

public static <T> T coalesce(T... vals) { // Hunting for non-nulls, beware nulls! for (T value : vals) { if (value != null) { return value; } } return null; }

These can help perform similar nullity checks, and you could call them statically to reuse them throughout your codebase:

import static your.package.NullityUtility.coalesce; ... // Null protest march is coming this way! String output = coalesce(variable, "defaultVal");

While this can help cleaning up your code, be cautious if these methods do not short-circuit, as they might end up evaluating more expressions than necessary, which could have a giant waving sign that screams "HEY! PERFORMANCE ISSUES OVER HERE!".

Going deeper with Java's Optional Class

Java's Optional class, introduced in Java 8, becomes your handy tool when you really want to play it safe with null values:

String output = Optional.ofNullable(yourVariable).orElse("defaultVal");

In cases of complex objects with possibilities of nested null checks, you could combine method references with Optional to perform an elegant defaulting:

String countryCode = Optional.ofNullable(person) .flatMap(Person::getAddress) // Toss a coin to your Person. Oh address plenty! .flatMap(Address::getCountry) .flatMap(Country::getCode) .orElse("Unknown Code");

Though beneficial, recognize that overuse of Optional can lead to increased verbosity, and is best used when there's an actual semantically optional value.

Taking performance into the equation

One crucial thing to bear in mind is the balance between performance and readability. While the use of utility methods or the Optional class can enhance readability, they can potentially add some overhead to your application's performance. Do not forget to keep the behavior of short-circuiting in mind when dealing with null checks in performance-sensitive code. Remember, the fastest code is the code that never runs.