Java : NullPointerException with Examples

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


Summary

Thrown when an application attempts to use null in a case where an object is required.

Class diagram

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

try {
    final String str2 = null;
    final var upperCase2 = str2.toUpperCase();
} catch (NullPointerException e) {
    System.out.println("NullPointerException! : " + e.getMessage());
}

// Result
// ↓
//NullPointerException! : Cannot invoke "String.toUpperCase()" because "str2" is null
class Sample {
    private final String value;

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

    @Override
    public String toString() {
        return value;
    }
}

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

try {
    final var bbb = new Sample(null);
} catch (NullPointerException e) {
    System.out.println("NullPointerException! : " + e.getMessage());
}

// Result
// ↓
//NullPointerException! : value is null

Constructors

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

Methods

String getMessage ()

Returns the detail message string of this throwable.

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

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