Java : NullPointerException - API Examples

NullPointerException (Java SE 18 & JDK 18) API Examples.
You will find code examples on most NullPointerException methods.


Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value.

Class diagram

final String str1 = "abcd";
final var upperCase1 = str1.toUpperCase();
System.out.println(upperCase1); // ABCD

final String str2 = null;

// java.lang.NullPointerException:
//   Cannot invoke "String.toUpperCase()" because "str2" is null
final var upperCase2 = str2.toUpperCase();
class Sample {
    private final String value;

    Sample(String value) {
        this.value = Objects.requireNonNull(value, "value is null");

    public String toString() {
        return value;

final var aaa = new Sample("abcd");
System.out.println(aaa); // abcd

// java.lang.NullPointerException: value is null
final var bbb = new Sample(null);


NullPointerException ()

Constructs a NullPointerException with no detail message.

final var e = new NullPointerException();
System.out.println(e); // java.lang.NullPointerException

NullPointerException (String s)

Constructs a NullPointerException with the specified detail message.

final var e = new NullPointerException("abcde");
System.out.println(e); // java.lang.NullPointerException: abcde
System.out.println(e.getMessage()); // abcde


String getMessage ()

Returns the detail message string of this throwable.

Please see NullPointerException(String s).

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.

Related posts

To top of page