Course contentsShow
← Java
Lesson 292 of 2,8707. Reference Types and Object FundamentalsFree lesson

Testing for null with == and equals

Learn the safe way to test if a reference is null and why calling equals on null throws an exception.

Testing for null with == and equals

You'll learn the safe way to check if a reference is null and why calling equals on null causes crashes.

The Core Idea

When you need to test whether a reference variable points to null, you must use the == operator—never call equals on a potentially null reference. Here's why: if you try myObject.equals(something) when myObject is null, you're asking a non-existent object to do work, which immediately throws a NullPointerException.

Think of it like this: if you have an empty mailbox slot (null reference), you can check whether the slot is empty by looking at it (== null), but you can't ask the non-existent letter inside to compare itself to something—there's nothing there to respond!

Safe null Checking

String name = null;

// CORRECT: Use == to test for null
if (name == null) {
    System.out.println("No name provided");
}

// DANGEROUS: This crashes!
// if (name.equals("John")) { ... }  // NullPointerException!

// SAFE PATTERN: Check null first
if (name != null && name.equals("John")) {
    System.out.println("Hello, John!");
}

// SAFER PATTERN: Put the known non-null object first
if ("John".equals(name)) {  // Safe even if name is null
    System.out.println("Hello, John!");
}

The last pattern works because "John" is definitely not null, so calling .equals(name) on it is safe—equals methods are designed to handle a null argument gracefully by returning false.

Key Takeaway: Always use == null or != null to test for null references. Never call methods (including equals) on a reference that might be null without checking first, or put the guaranteed non-null object on the left side of equals.