Java
Enhanced For Loop
Null Check
Error Handling
Programming

Null check in a Java enhanced for loop

Codemia Knowledge Hub ·

A Java enhanced for loop (for-each) throws a NullPointerException when the collection or array is null, so check for null before the loop. You can do that with a plain if, with Optional.ofNullable, or with a reusable helper method.

Why a null collection throws

The enhanced for loop has this structure:

java
for (Type variable : collection) {
    // use variable
}

Type is the element type, variable refers to each element in turn, and collection is either an array or an instance of java.util.Collection.

Under the hood the loop calls .iterator() (for collections) or reads .length (for arrays). Neither can be invoked on a null reference, so a null collection causes a NullPointerException.

Three ways to guard the loop

  1. Explicit null check:
    Check that the collection is not null before the loop.
java
1   if (collection != null) {
2       for (Type variable : collection) {
3           // use variable
4       }
5   } else {
6       // handle null case
7   }
  1. Use Optional:
    Java 8 introduced Optional, which can wrap a possibly null value.
java
1   Optional.ofNullable(collection).ifPresent(col -> {
2       for (Type variable : col) {
3           // use variable
4       }
5   });
  1. Helper methods:
    Write a utility function that handles null for you.
java
1   public static <T> void forEach(Iterable<T> iterable, Consumer<T> action) {
2       if (iterable != null) {
3           for (T item : iterable) {
4               action.accept(item);
5           }
6       }
7   }
8
9   // Usage
10   forEach(collection, item -> {
11       // use item
12   });
AspectDescription
Structurefor (Type variable : collection) &#123; &#125;
Null Scenario ConsequenceNullPointerException if collection is null
Pre-Loop CheckEvaluate if collection is not null before the loop
Java 8 FeatureUse Optional to encapsulate potential null collections
Utility MethodsImplement reusable functions to handle null cases during iteration

Enhanced vs traditional for loops

Traditional for loops give more control (initialization, condition and update in one line), which makes them flexible but more verbose. Enhanced for loops hide that and give cleaner code when all you need is iteration.

The enhanced loop has no index access. If you need to use or modify the index during iteration, fall back to a traditional for loop.

In most cases both perform the same. For primitive arrays, traditional loops may be slightly faster because they avoid the iterator pattern used internally by enhanced for loops.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms