Post Reply 
 
Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Null-safe Type in Java 7: New way to handle NullPointerException
02-13-2011, 02:58 PM
Post: #1
Null-safe Type in Java 7: New way to handle NullPointerException
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.
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:



Send your comments, Suggestions or Queries regarding this site at info@tutorials4u.net

Copyright © 2010 Tutorials4u.net All Rights Reserved