Library contents

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

  1. Start with No string supplied
  2. Do this Try to read its length
  3. Result No length available
Checking for a missing value first lets the program choose a default before accessing a member.

Syntax

Java syntax
phone.strip()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Print 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.

ResultAsk for a phone number
Main.java
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");
        }
    }
}
Output
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.

Advertisements

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.

ResultEmail only
Main.java
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"));
    }
}
Output
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.

GivenExtension 204
Worked resultContact available
Code and output in Java
Java source
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");
        }
    }
}
Output
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.

Documentation for NullPointerException