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.

Answer from Andrzej Doyle on Stack Overflow
🌐
GitHub
gist.github.com › kherge › 819b682f271d024bb093583fb2044cdd
Null Coalescing in Java · GitHub
At the time of this writing, Java does not provide a null coalescing operator.
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8289289
[JDK-8289289] Add the `null`‑coalescing operator (`a ?? b`)
Foo.b() ?? Foo.c(); ``` ```jasm 0 invokestatic Foo.a:()LBar; // stack: a:LBar; 3 dup; // stack: a:LBar; a:LBar; 4 ifnonnull L17; // stack: a:LBar; 6 pop; // stack: 7 invokestatic Foo.b:()LBar; // stack: b:LBar; 10 dup; // stack: b:LBar; b:LBar; 11 ifnonnull L17; // stack: b:LBar; 13 pop; // stack: 14 invokestatic Foo.c:()LBar; // stack: c:LBar; 17 L17: areturn; ``` --------------------------------------------- This operator is different from `Objects.requireNonNullElse(a, b)`, as `Objects.requireNonNullElse` evaluates both `a` and `b`, regardless of the nullity of `a`, and requires at least one of them to be non‑`null`. `Objects.requireNonNullElseGet(a, () => b)` is closer, in that evaluation of `b` is deferred, but `Objects.requireNonNullElseGet` requires `b` to be non‑`null`, whereas the `a ??

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.

Answer from Andrzej Doyle on Stack Overflow
🌐
Medium
medium.com › @mcaliman › c-null-coalescing-operator-in-java-2788ad6c2496
C# null-coalescing operator in Java | by Massimo Caliman | Medium
January 24, 2020 - In C# the ?? operator is called the null-coalescing operator. Here’s an example of use: ... It returns the left-hand operand if it is not null, otherwise it returns the right-hand operand. A possible alternative in Java of C# ??
🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - The operator can also be used multiple times in the same expression: ... Once a non-null value is assigned to number, or it reaches the final value (which may or may not be null), the expression is completed. If, for example, a variable should be changed to another value if its value evaluates to null, since C# 8.0 the ??= null coalescing assignment operator can be used:
🌐
Benji's Blog
benjiweber.co.uk › blog › 2013 › 12 › 08 › null-coalescing-in-java-8
Null Coalescing in Java 8 - Benji's Blog
December 8, 2013 - We have been able to do something similar with Java for some time using a varargs method like this: public static <T> T coalesce(T... ts) { for (T t : ts) if (t != null) return t; return null; } String result = coalesce(somethingPossiblyNull(), somethingElse(), "defaultValue");
Top answer
1 of 1
2

You could write a function that takes a value and a getter to transform it, like so

public static <T1, T2> T1 coalesce(T2 value, Function<T2,T1> f1){
    return f1.apply(value);
}

which you would then call like so coalesce(value, Clazz::getA).

For every step further in your chain, you need an additional Function in your coalesce function, like so

public static <T1, T2, T3> T1 coalesce(T3 value, Function<T3,T2> f1, Function<T2,T1> f2){
    T2 t2 = f1.apply(value);
    if(t2 == null)
        return null;    
    return f2.apply(t2);
}

for a depth of two, and

public static <T1, T2, T3, T4> T1 coalesce(T4 value, Function<T4,T3> f1, Function<T3,T2> f2, Function<T2,T1> f3){
    T3 t3 = f1.apply(value);
    if(t3 == null)
        return null;
    T2 t2 = f2.apply(t3);
    if(t2 == null)
        return null;
    return f3.apply(t2);
}

for a depth of three and so on for further depths.

Example code:

    A test1 = new A(null);
    A test2 = new A(new B(null));
    A test3 = new A(new B(new C(null)));
    A test4 = new A(new B(new C("1234")));

    System.out.println(coalesce(test1, A::getB, B::getC, C::getS));
    System.out.println(coalesce(test2, A::getB, B::getC, C::getS));
    System.out.println(coalesce(test3, A::getB, B::getC, C::getS));
    System.out.println(coalesce(test4, A::getB, B::getC, C::getS));

    System.out.println(coalesce(test2, A::getB));
    System.out.println(coalesce(test3, A::getB, B::getC));

A is a class with a member of class B, B is a class with a member of class C, C is a class with a member of class String, with appropriate getters. Output is as expected:

null
null
null
1234    
B@776ec8df
C@41629346

Nulls for the first three cases, where the string in C is null, the fourth has the value of the string, and fifth and sixth return objects of type B and C respectivelly.

I don't see a way to make the code much shorter unfortunately.

Find elsewhere
🌐
Hacker News
news.ycombinator.com › item
Migrating from Java 8 to Java 17 II: Notable API Changes Since Java 8 | Hacker News
June 30, 2024 - What is it with Java deciding "Why use 2 characters when 40 will do?" Is it to much to ask for a ?? or ?: operator · List<String> trimAndAdd(List<String> input, String newItem) { List<String> result = new ArrayList<>(input.size() + newItem == null ? 0 : 1);
🌐
Reddit
reddit.com › r/programminglanguages › thoughts on the null coalescing (??) operator precedence?
r/ProgrammingLanguages on Reddit: Thoughts on the Null Coalescing (??) operator precedence?
April 30, 2024 -

Many languages have a "null-coalescing" operator: a binary operator used to unwrap an optional/nullable value, or provide a "default" value if the LHS is null/none. It's usually spelled ?? (as in Javascript, Swift, C#, etc.).

I'm pondering the precedence of such an operator.

Why not just use no precedence? Parenthesis! S-expressions! Polish!

All interesting ideas! But this post will focus on a more "C-style" language perspective.


As for ??, it seems like there's a bit of variety. Let's start with a kind of basic operator precedence for a hypothetical C-style statically typed language with relatively few operators:

precoperatorstypes
1Suffixes: a()-> any type
2High-prec arithmetic: a * binteger, integer -> integer
3Low-prec arithmetic: a + binteger, integer -> integer
4Comparisons: a == binteger, integer -> boolean
5Logic: a && bboolean, boolean -> boolean

There are subtly differences here and there, but this is just for comparisons. Here's how (some) different languages handle the precedence.

  • Below #5:

  • C#

  • PHP

  • Dart

  • Equal to #5

  • Javascript (Kinda; ?? must be disambiguated from && and ||)

  • Between #3 and #4:

  • Swift

  • Zig

  • Kotlin

So, largely 2 camps: very low precedence, or moderately low. From a brief look, I can't find too much information on the "why" of all of this. One thing I did see come up a lot is this: ?? is analogous to ||, especially if they both short-circuit. And in a lot of programming languages with a looser type system, they're the same thing. Python's or comes to mind. Not relevant to a very strict type system, but at least it makes sense why you would put the precedence down that. Score 1 for the "below/equal 5" folk.


However, given the divide, it's certainly not a straightforward problem. I've been looking around, and have found a few posts where people discuss problems with various systems.

  • https://forums.swift.org/t/nil-coalescing-operator-precedence/2954

  • https://www.codeproject.com/Tips/721145/Beware-The-null-coalescing-operator-is-low-in-the

These seem to center around this construct: let x = a() ?? 0 + b() ?? 0. Operator precedence is largely cultural/subjective. But if I were a code reviewer, attempting to analyze a programmer's intent, it seems pretty clear to me that the programmer of this wanted x to equal the sum of a() and b(), with default values in case either were null. However, no one parses ?? as having a higher precedence than +.

This example might be a bit contrived. To us, the alternate parse of let x = a() ?? (0 + b()) ?? 0 because... why would you add to 0? And how often are you chaining null coalescing operators? (Well, it can happen if you're using optionals, but it's still rare). But, it's a fairly reasonable piece of code. Those links even have some real-world examples like this people have fallen for.


Looking at this from a types perspective, I came to this conclusion; In a strongly-typed language, operator precedence isn't useful if operators can't "flow" from high to low precedence due to types.

To illustrate, consider the expression x + y ?? z. We don't know what the types of x, y, and z are. However, if ?? has a lower precedence than +, this expression can't be valid in a strictly typed language, where the LHS of ?? must be of an optional/nullable type.

If you look back at our hypothetical start table, you can see how operator types "flow" through precedence. Arithmetic produces integers, which can be used as arguments to comparisons. Comparisons produce booleans, which can be used as arguments to logical operators.

This is why I'd propose that it makes sense for ?? to have a precedence, in our example, between 1 and 2. That way, more "complex" types can "decay" though the precedence chain. Optionals are unwrapped to integers, which are manipulated by arithmetic, decayed to booleans by comparison, and further manipulated by logic.


Discussion questions:

  1. What are some reasons for choosing the precedence of ?? other than the ones discussed?

  2. Have any other languages done something different with the precedence, and why?

  3. Has anyone put the precedence of ?? above arithmetic?

Thanks!

🌐
Reddit
reddit.com › r/java › how hard would it be to add a safe call operator to the java language?
r/java on Reddit: How hard would it be to add a safe call operator to the Java language?
September 4, 2021 -

Checking for null is quite verbose in Java. The current best practice is to either use Nullability annotations or Optional<T>. Personally, I'm in the annotations camp. Yes, optional is very useful in streams but I don't like the cognitive and runtime overhead it implies anywhere else.

My dream would be if one day nullability would be added to the type system. Obviously, that's a lot of work. But wouldn't be a pragmatic first step, to reduce just the boilerplate of null checks with a safe call operator? The compiler could surely rewrite this code:

if (getLoggedInUser()?.isPowerUser()) {
}

To this:

if (getLoggedInUser() != null && getLoggedInUser().isPowerUser()) {
}

To avoid an unexpected double method invocation, it could assign to ad hoc created temp variables:

User generatedSafeCall1;
if ((generatedSafeCall1 = getLoggedInUser()) != null && generatedSafeCall1.isPowerUser()) {
}

I believe this would end a lot of complaints about null handling in Java. Since only new code would use the ?. operator, backwards compatibility shouldn't be an issue either. Are there any downsides that I'm missing?

🌐
nipafx
nipafx.dev › java-pirate-elvis-operator
Roll Your Own Pirate-Elvis Operator // nipafx
March 16, 2015 - Java has no Elvis operator (or null coalescing operator / null-safe member selection) but with lambda expressions / method references you can roll your own.
🌐
CopyProgramming
copyprogramming.com › howto › alternative-for-null-coalescing-operator
Java Null Coalescing: Complete Guide to Alternatives, 2026 Best Practices & New Features
January 3, 2026 - Java does not have a native null coalescing operator like C#'s or Kotlin's , but multiple proven alternatives exist to handle null values safely and elegantly. The lack of a built-in null coalescing operator has been a long-standing limitation in Java, but the language now offers sophisticated ...
🌐
CodingTechRoom
codingtechroom.com › question › -java-null-coalescing-equivalent
What is the Java Equivalent of the C# Null Coalescing Operator? - CodingTechRoom
The C# null coalescing operator (??) provides a simple syntax for returning the first non-null value. While Java does not have a direct equivalent, similar functionality can be achieved using the ternary conditional operator or the Optional class introduced in Java 8.
🌐
Useful
useful.codes › null-coalescing-operator-in-java
Null Coalescing Operator in Java | Useful Codes
The Null Coalescing Operator (??) is a concept borrowed from languages like C# and PHP, allowing developers to handle null values gracefully. While Java does not have a direct null coalescing operator, similar functionality can be achieved using the Optional class introduced in Java 8.
🌐
javaspring
javaspring.net › blog › java-null-coalesce
Java Null Coalescing: An In-Depth Guide — javaspring.net
And in Java 14, the null coalescing operator (??) was introduced in the form of preview feature, which further simplifies the null handling process.
🌐
Ryanmichaelrichardson
ryanmichaelrichardson.com › posts › 04-17-22-null-operators
Java Null Operators | Hi, I'm Ryan
In layman’s terms, “If country is not null and getState() does not return null, return the value of the getCity() method, otherwise, return null” · Java unfortunately does not have support for these operators.
🌐
Reddit
reddit.com › r/java › draft jep: null-restricted and nullable types (preview)
r/java on Reddit: Draft JEP: Null-Restricted and Nullable Types (Preview)
August 2, 2024 - So this branches out with O(2n) with n = number of null-safe accesses and no branch prediction of a cpu will be able to compensate that. More replies More replies More replies ... This is definitely eating away at the reasons to use Kotlin, but the way Kotlin handles lambdas is still leagues ahead of Java. I would like to see some improvements there. ... Well, kotlin’s lambdas are very hard to parse, imo, especially when combined with infix operators and everything else.
🌐
Baeldung
baeldung.com › home › java › core java › how to implement elvis operator in java
How to Implement Elvis Operator in Java | Baeldung
May 5, 2024 - The operator evaluates the expression on its left-hand side and returns it if it isn’t null. If the expression on the left-hand side evaluates to null, it returns the expression on the right-hand side instead. For example, in Kotlin, we can write val name = person.name?: “Unknown” to return the person’s name if it’s not null, or “Unknown” if it is.
🌐
Winterbe
winterbe.com › posts › 2015 › 03 › 15 › avoid-null-checks-in-java
Avoiding Null Checks in Java 8 - winterbe
Since null checks are kinda cumbersome and painful many languages add special syntax for handling null checks via null coalescing operators - also known as elvis operator in languages like Groovy or Kotlin. Unfortunately Java doesn’t provide such a syntactic sugar.