Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 943
Siddharth Kamaria Avatar asked Nov 22 '14 05:11

Siddharth Kamaria


People also ask

Can you catch NullPointerException in Java?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

How do I check NullPointerException?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

WHAT IS NULL pointer check in Java?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

How do you check if it is null in Java?

To check if a string is null or empty in Java, use the == operator.


1 Answers

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)

like image 195
Hari Menon Avatar answered Oct 21 '22 11:10

Hari Menon