dcsimg
June 22, 2018
Hot Topics:

Java 7 Feature: Asserting Non-Null Objects

  • March 30, 2011
  • By Leonard Anghel
  • Send Email »
  • More Articles »

Starting with JDK 7, you can assert non-null objects with two java.util.Objects methods:

  • <T> T nonNull(T obj): This method checks that the specified object reference is not null. It returns obj if the reference is not null, or NullPointerException otherwise.
  • <T> T nonNull(T obj, String message): This method checks that the specified object reference is not null and throws a customized NullPointerException if it is. It returns obj, the object reference to check for nullity, or message, a detailed message to be used in the event that a NullPointerException is thrown.

Here is an example of the two java.util.Objects methods:

package jdk7_nonnull;

import java.util.Objects;

public class Main {

public static void main(String[] args) {

//create a null String object
String nullString = null;
//create a non-null String object
String nonNullString = "Java 7 Rocks!";

//returns nonNullString
String c_nonNullString = Objects.nonNull(nonNullString);
System.out.println(c_nonNullString);

//throw a NullPointerException
String c_nullString_1 = Objects.nonNull(nullString);

//throw a customize NullPointerException
String c_nullString_2 = Objects.nonNull(nullString, "This String is null!");
}
}

Here's the output:

Java 7 Rocks!
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.nonNull(Objects.java:201)
at jdk7_nonnull.Main.main(Main.java:30)
Java Result: 1


Originally published on https://www.developer.com.


Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

Sitemap

×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date