Tutorials4u.net Forum
Null-safe Type in Java 7: New way to handle NullPointerException - Printable Version

+- Tutorials4u.net Forum (http://www.tutorials4u.net/forum)
+-- Forum: Discussion Forum (/forumdisplay.php?fid=1)
+--- Forum: JAVA (/forumdisplay.php?fid=2)
+--- Thread: Null-safe Type in Java 7: New way to handle NullPointerException (/showthread.php?tid=90)


Null-safe Type in Java 7: New way to handle NullPointerException - tutorials4u - 02-13-2011 02:58 PM

Update: This feature has been removed from the final feature list that is being included in Java 7. Thanks @Stephen and @Stefan for the comments. Please refer to Project Coin for more details.

NullPoniterException is one of the most common exception encountered in Java programming. When I searched “NullPointerException” in Google, it gave about 6,130,000 results! This proves how pervasive the exception is and how much effort a developer has to put in writing java code free from null pointer exception.

Suppose we have a method to fetch postal code of a person’s address:

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


Now check the above syntax. We have done lots of if (null != object) checks to avoid NullPointerException.

Java 7 (Codename: Dolphine) will change the way we do Null handling in our code. Java 7 will be released in first half of 2010. If we write above code using Java 7 Null-safe Type (also called Null-ignore invocation), it will look like:

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


Null-ignore invocation is concerned with dealing with possible null values in calling one or especially a chain of methods. Check the syntax ?. while calling method on an object. This is Null-safe operator in Java 7. Thus, you can avoid lots of if (null != object) checks in Java 7.