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?
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.
To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With