Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example:

if (someobject != null) {

    someobject.doCalc();

}

This avoids a NullPointerException, when it is unknown if the object is null or not.

1 Answer

0 votes
by (46k points)

Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  

  return person?.getAddress()?.getPostcode();  

}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.

 An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.

The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...