Java : NullPointerException with Examples
NullPointerException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most NullPointerException methods.
Summary
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 ()
final var e = new NullPointerException();
System.out.println(e); // java.lang.NullPointerException
NullPointerException (String s)
final var e = new NullPointerException("abcde");
System.out.println(e); // java.lang.NullPointerException: abcde
System.out.println(e.getMessage()); // abcde
Methods
String getMessage ()
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
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- CancellationException
- ClassCastException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalArgumentException
- IllegalStateException
- IndexOutOfBoundsException
- NoSuchElementException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable