Is there a ?. operator for Java to perform null pointer checking?

3.5k views Asked by At

When I code I am frustrated with null checks. Especially while coding data structures!

I have to do it as

String val;
if(a != null && a.child != null)
    val = a.child.getValue();
else
    val = null;

Something sort of this...

Is there a operator like ?. (which is a part of C#) for Java to shorten the burden ?

ะก# example:

String val = a?.child?.getValue();
6

There are 6 answers

0
user949300 On BEST ANSWER

There is no ?. operator in Java, so, as Hari notes, you have to do things the "long winded" way. However, one could argue that this is a good thing, as it discourages the use of nulls.

For example, in OP's code, why are you setting val to null if a or it's child is not there? Let's assume that this is a function and val gets returned. This is a code smell: it just pushes the requirement for yet another null check to users of your code. It becomes an endless cycle of null checks, completely cluttering the code and confusing the logic, because maintenance programmers often can't tell if this is legitimate logic, or a paranoid former programmer is quietly ignoring errors. Don't mimic PHP!. Quoting from that excellent rant:

"When faced with either doing something nonsensical or aborting with an error, it (PHP) will do something nonsensical."

PHP makes a horrible design choice. It is far better to abort with an error than do something nonsensical.

Instead, you should be asking questions like:

  1. What does it mean for a to be null? Is this a programming error? If so, throw some RuntimeException / IllegalArgumentException. If this is critical code and you "can't fail", at least log that you are papering over something fishy, so maybe it will get fixed.
  2. What if a.child.getValue() itself returns null? How will my caller tell the difference between that null and the "a or child is null" null? They can't.
  3. If there is a good default value, use it. If you are using a Collection or Array, don't pass null to mean "empty". Pass a Collections.emptyXXX(), e.g. an emptyList, or an empty array. Instead of setting a String to null, consider setting it to the empty string "". BTW, this makes your hashCode(), equals(), and compareTo() much simpler!
  4. Use the Null Object Pattern.. If a is an instance of a Foo, define a static final Foo.NULL which does have a child whose value is itself something "nullish" - either null or "".

Sometimes you really can't do any of these things. There are valid reasons for arguments to be null, or you must allow for backwards compatibility with a previous bad design or 3rd party library. IMO, this should be rare, and you should document what happens. And maybe you should return something other than null (or 0) to reflect this. For example

/**
   countPeople
   @param  node  null means the foobar can't connect to the database, 
   @return       Foobar.ERR_NO_DB if node is null
*/

In OP's example, it looks like a may be some sort of XML node, and the Java XML interfaces are huge and creating a good NULL object for one of them would be a huge undertaking. (Hmm, maybe a good little open source project?). However, in that case, you will likely be calling a.child.getValue() a lot. Write a little utility function to handle this and handle the nulls. Instead of long winded null checks everywhere, at least they are encapsulated in a few utility methods. DRY. And, arguably the fact that the checks are long winded, encouraged you to do a better design. So the lack of the ?. operator was a good thing, right? :-)

3
Hari Menon On

No

As with most things in Java, you have to do it in the long winded way. Hey, at least it is more readable - if you have to do a null check, why not make it explicit and easily visible (playing devil's advocate here)

3
Elliott Frisch On

There is no such operator in Java. The closest thing I can think of, that Java supports, is Yoda conditions which would allow you to check for a value against a constant like

if ("test".equals(str))

instead of

if (str != null && str.equals("test"))
2
icza On

The ?. operator doesn't exist in Java.

The "most" compact what you can do is the ?: ternary operator which you can "chain":

String val = a != null && a.child != null ? a.child.getValue() : null;

or

String val = a == null ? null : a.child == null ? null : a.child.getValue();
0
S. M. Mohiuddin On

No there is no ?. operator in JAVA. You can use != operator for checking not null

String val = (a != null && a.child !== null) ? a.child.getValue() : null; 
0
Syed Mohammad Shakil On

There is no such operator in Java.

 str != null && str.equals("test")