Course contentsShow
← Java
Lesson 794 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

NullPointerException: The Most Common Runtime Error

Understand when NullPointerException occurs and strategies to prevent it in your code.

NullPointerException: The Most Common Runtime Error

You'll learn when NullPointerException occurs and how to prevent it in your code.

What Is NullPointerException?

NullPointerException (often abbreviated NPE) is an unchecked exception that occurs when you try to use a reference variable that points to null as if it were pointing to an actual object. Since null means "no object," attempting to access methods or fields through it fails immediately.

Think of it like trying to open a door when there's no door there at all—just an empty doorway. You can't turn a doorknob that doesn't exist.

Common Triggers

You'll encounter NullPointerException when you:

  • Call a method on a null reference: myObject.doSomething()
  • Access a field of a null reference: myObject.fieldName
  • Attempt to get the length of a null array: myArray.length
  • Index into a null array: myArray[0]
  • Throw null as if it were a Throwable

Prevention Strategies

Check before using:

if (myObject != null) {
    myObject.doSomething();
}

Initialize carefully:

String name = "";  // Not null
List<String> items = new ArrayList<>();  // Not null

Use meaningful defaults:

public String getName() {
    return name != null ? name : "Unknown";
}

Validate method parameters:

public void process(String input) {
    if (input == null) {
        throw new IllegalArgumentException("Input cannot be null");
    }
    // safe to use input
}

Key Takeaway: NullPointerException happens when you treat null as an object—always verify references aren't null before using them, or ensure they're properly initialized to avoid this common runtime error.