I searched a while for an equal for C# 'nullable' in java and found that one of the closest ways is to use the wrapper classes; now I want to know is there an equal for the c# null coalescing operator (??) in java? (of course except an ordinary 'if' statement)
Asked
Active
Viewed 2,360 times
5
-
That is really cool and I want it, but sadly, no, there is no such thing in Java. – Sotirios Delimanolis Feb 12 '14 at 06:10
-
possible duplicate of [How to get the first non-null value in Java?](http://stackoverflow.com/questions/2768054/how-to-get-the-first-non-null-value-in-java) – AymenDaoudi Feb 12 '14 at 06:14
-
1Indeed the 'null' is very common in programming and it's very strange that there is such a big gap in java. – Mohsen Kamrani Feb 12 '14 at 06:18
-
@AymenDaoudi: As I already said I asked for a way other than if statements.(no doubt there is not much difference between the ' ? : ' operator and an 'if' statement) – Mohsen Kamrani Feb 12 '14 at 06:21
-
I also wish Java had a ?. operator where `a?.foo()` only invokes `foo()` and returns its return value if a is not null, otherwise just returns null. Likewise for field access: `a?.someField` would evaluate to null if a is null. – Andy Feb 19 '14 at 00:15
-
or an inverse of ??: `a ?=> b` evaluates to null if a is null, and evaluates to b if a is not null. That way you could do things like `Integer i = s ?=> Integer.parseInt(s);` – Andy Feb 19 '14 at 00:17
3 Answers
6
No there isn't a null coalescing operator, however; there is a pattern that can be used in Java 8 that essentially does the same thing. Just wrap the result of an operation in an Optional and then call the orElse method
final String myString = Optional.ofNullable(resultSet.getString(1))
.orElse("default");

Jason Thompson
- 4,643
- 5
- 50
- 74
-
1I really like this answer. You can also use the helpful `orElseGet(Supplier
)` method as well with this approach. – Pete Nov 21 '15 at 02:49
4
Direct answer, no it doesn't exist in java

AymenDaoudi
- 7,811
- 9
- 52
- 84
-
1Is there a way to ask the Oracle for the reason,if you are so sure? – Mohsen Kamrani Feb 12 '14 at 06:35
-
3I've asked the oracle, and it revealed to me this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html there, are all operators you can find in java and i can't find any coalescing operator, unless you use a ternary or an if-else statement which I guess you're not looking for, as said in another answer here, Guava did the same thing making of that a merhod, If Google made a method to fill that gap, that means that that gap really exists, hope this explains how sure I'm. – AymenDaoudi Feb 12 '14 at 07:42
-
-