Java 7 Feature: Asserting Non-Null Objects
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 returnsobjif the reference is not null, orNullPointerExceptionotherwise.<T> T nonNull(T obj, String message): This method checks that the specified object reference is not null and throws a customizedNullPointerExceptionif it is. It returnsobj, the object reference to check for nullity, ormessage, a detailed message to be used in the event that aNullPointerExceptionis 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
0 Comments (click to add your comment)
Networking Solutions



Solid state disks (SSDs) made a splash in consumer technology, and now the technology has its eyes on the enterprise storage market. Download this eBook to see what SSDs can do for your infrastructure and review the pros and cons of this potentially game-changing storage technology.