I was reading an article linked from a slashdot story, and came across this little tidbit:
Take the latest version of Java, which tries to make null-pointer checking easier by offering shorthand syntax for the endless pointer testing. Just adding a question mark to each method invocation automatically includes a test for null pointers, replacing a rat's nest of if-then statements, such as:
public String getPostcode(Person person) { String ans= null; if (person != null) { Name nm= person.getName(); if (nm!= null) { ans= nm.getPostcode(); } } return ans }With this:
public String getFirstName(Person person) { return person?.getName()?.getGivenName(); }
I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.
Thanks!
EDIT: Link to the article: http://infoworld.com/d/developer-world/12-programming-mistakes-avoid-292
Java does not have the exact syntax but as of JDK-8, we have the Optional API with various methods at our disposal. So, the C# version with the use of null conditional operator:
can be written as follows in Java with the Optional API:
if any of
person
,getName
orgetGivenName
is null then null is returned.If this is not a performance issue for you, you can write
You can test the code which you have provided and it will give syntax error.So, it is not supported in Java. Groovy does support it and it was proposed for Java 7 (but never got included).
However, you can use the Optional provided in Java 8. This might help you in achieving something on similar line. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Example Code for Optional
There was a proposal for it in Java 7, but it was rejected:
http://tech.puredanger.com/java7/#null
That's actually Groovy's safe-dereference operator. You can't use it in pure Java (sadly), so that post is simply wrong (or more likely slightly misleading, if it's claiming Groovy to be the "latest version of Java").
See: https://blogs.oracle.com/darcy/project-coin:-the-final-five-or-so (specifically "Elvis and other null safe operators").
The result is that this feature was considered for Java 7, but was not included.