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.
🌐
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 - ts) { for (T t : ts) if (t != null) return t; return null; } String result = coalesce(somethingPossiblyNull(), somethingElse(), "defaultValue"); (There is a similar method on Guava’s Objects class); It looks nice and avoids the need for ugly ifs in some places. However, unfortunately it means that somethingElse() would have to be evaluated even if somethingPossiblyNull() returned a non-null value. This is not what we want if these are expensive, so we had to fall back to something less clean. In Java 8 thanks to lambdas & method references we can do this lazily.
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8289289
Loading...
--------------------------------------------- Having a dedicated operator for this common‑ish case would allow the compiler to emit more compact bytecode for this: ```java return Foo.a() ?? Foo.b(); ``` ```jasm 0 invokestatic Foo.a:()LBar; // stack: a:LBar; 3 dup; // stack: a:LBar; a:LBar; 4 ifnonnull L10; // stack: a:LBar; 6 pop; // stack: 7 invokestatic Foo.b:()LBar; // stack: b:LBar; 10 L10: areturn; ``` The `null`‑coalescing operator can be chained: ```java return Foo.a() ??
🌐
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# ??
🌐
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!

🌐
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);
🌐
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 solutions including , the ternary operator, pattern matching, and emerging nullability markers through jSpecify.
Find elsewhere
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.

🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand.
🌐
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?

🌐
Winterbe
winterbe.com › posts › 2015 › 03 › 15 › avoid-null-checks-in-java
Avoiding Null Checks in Java 8 - winterbe
We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row.
🌐
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.
🌐
Reddit
reddit.com › r/java › java and nulls
r/java on Reddit: Java and nulls
August 23, 2024 -

It appears the concept of nulls came from Tony Hoare back in 1965 when he was working on Algol W. He called it his "billion dollar mistake". I was wondering if James Gosling has ever expressed any thoughts about wether or not adding nulls to Java was a good or bad thing?

Personally, coming to Java from Scala and Haskell, nulls seem like a very bad idea, to me.

I am considering making an argument to my company's engineering team to switch from using nulls to using `Optional` instead. I am already quite aware of the type system, code quality, and coding speed arguments. But I am very open to hearing any arguments for or against.

🌐
javaspring
javaspring.net › blog › java-null-coalesce
Java Null Coalescing: An In-Depth Guide — javaspring.net
Null coalescing is a concept that simplifies the process of handling null values. The basic idea is to check if a variable is null, and if it is, provide an alternative (default) value.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-nullish-coalescing-operator
JavaScript Nullish Coalescing(??) Operator - GeeksforGeeks
The nullish coalescing (??) operator is used to handle null and undefined values in JavaScript.
Published   March 2, 2020
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.