Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-safe Method invocation Java7

Tags:

java

java-7

I want to get details about this feature of Java7 like this code

public String getPostcode(Person person)
{
    if (person != null)
    {
        Address address = person.getAddress();
        if (address != null)
        {
            return address.getPostcode();
        }
    }
    return null;
}

Can be do something like this

public String getPostcode(Person person)
{
    return person?.getAddress()?.getPostcode();
}

But frankly its not much clear to me.Please explain?

like image 726
Subodh Joshi Avatar asked Aug 09 '13 17:08

Subodh Joshi


People also ask

What is null safe in Java?

Null-safety ensures that we have added proper checks in the code to guarantee the object reference cannot be null or possible safety measures are taken when an object is null, after all. Since NullPointerException is a runtime exception, it would be hard to figure out such cases during code compilation.

IS null == null in Java?

To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.

How do you check if it is null in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.


2 Answers

Null-safe method invocation was proposed for Java 7 as a part of Project Coin, but it didn't make it to final release.

See all the proposed features, and what all finally got selected here - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC


As far as simplifying that method is concerned, you can do a little bit change:

public String getPostcode(Person person) {

    if (person == null) return null;
    Address address = person.getAddress();
    return address != null ? address.getPostcode() : null;
}

I don't think you can get any concise and clearer than this. IMHO, trying to merge that code into a single line, will only make the code less clear and less readable.

like image 67
Rohit Jain Avatar answered Oct 13 '22 23:10

Rohit Jain


If I understand your question correctly and you want to make the code shorter, you could take advantage of short-circuit operators by writing:

if (person != null && person.getAddress() != null)
    return person.getAddress().getPostCode();

The second condition won't be checked if the first is false because the && operator short-circuits the logic when it encounters the first false.

like image 44
Kon Avatar answered Oct 13 '22 23:10

Kon