Java NullPointerException
Calling an instance method through a null reference throws NullPointerException. An optional field needs a fallback before the application formats it.
A simple example
NullPointerException
- Start with No string supplied
- Do this Try to read its length
- Result No length available
Syntax
phone.strip()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint a label when the phone number is missing
A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.
class Main {
public static void main(String[] args) throws Exception {
String phone = null;
try {
System.out.println(phone.strip());
} catch (NullPointerException missing) {
System.out.println("Ask for a phone number");
}
}
}
Ask for a phone number
The call to strip fails because there is no String to format. The next example handles this expected case before it becomes an exception.
Print a contact card with a default
A club imports members from a form where the phone number is optional. Its desk still needs to print a card for every member, including those who prefer email.
import java.util.Objects;
class Main {
public static void main(String[] args) throws Exception {
String phone = null;
System.out.println(Objects.requireNonNullElse(phone, "Email only"));
}
}
Email only
Objects.requireNonNullElse supplies a printable label for the missing value.
Print an existing extension
A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
Objects.requireNonNull("204");
System.out.println("Contact available");
} catch (NullPointerException problem) {
System.out.println("Ask for contact");
}
}
}
Contact available
What to watch for
Catch a bad value where it enters the system. Catching every NullPointerException around a whole request can hide a programming mistake.