Java Utils - Objects.requireNonNull() Examples

Code Snippets Java Utils Java 


Class:

java.util.Objects

java.lang.Objectjava.lang.Objectjava.util.Objectsjava.util.ObjectsLogicBig

Methods:

These methods check that the specified object reference is not null. They are useful for parameter validation in methods and constructors.

public static <T> T requireNonNull(T obj)
public static <T> T requireNonNull(T obj, String message)
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)

Examples


package com.logicbig.example.objects;

import java.util.Objects;

public class RequireNonNullExample {

public static void main(String... args) {
String str = null;
str = Objects.requireNonNull(str);
}
}

Output

Caused by: java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at com.logicbig.example.objects.RequireNonNullExample.main(RequireNonNullExample.java:14)
... 6 more




package com.logicbig.example.objects;

import java.util.Objects;

public class RequireNonNullExample2 {

public static void main(String... args) {
String str = null;
str = Objects.requireNonNull(str, "str cannot be null");
}
}

Output

Caused by: java.lang.NullPointerException: str cannot be null
at java.util.Objects.requireNonNull(Objects.java:228)
at com.logicbig.example.objects.RequireNonNullExample2.main(RequireNonNullExample2.java:14)
... 6 more




package com.logicbig.example.objects;

import java.util.Objects;

public class RequireNonNullExample3 {

public static void main(String... args) {
String str = null;
//useful when creating the message is expensive
Objects.requireNonNull(str, RequireNonNullExample3::createMessage);
}

private static String createMessage() {
return "a demo string";
}
}

Output

Caused by: java.lang.NullPointerException: a demo string
at java.util.Objects.requireNonNull(Objects.java:290)
at com.logicbig.example.objects.RequireNonNullExample3.main(RequireNonNullExample3.java:15)
... 6 more




See Also