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:
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
- Explicit null check:
Check that the collection is notnullbefore the loop.
- Use Optional:
Java 8 introducedOptional, which can wrap a possiblynullvalue.
- Helper methods:
Write a utility function that handlesnullfor you.
| Aspect | Description |
| Structure | for (Type variable : collection) { } |
| Null Scenario Consequence | NullPointerException if collection is null |
| Pre-Loop Check | Evaluate if collection is not null before the loop |
| Java 8 Feature | Use Optional to encapsulate potential null collections |
| Utility Methods | Implement 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.
Related reading
- NullPointerException in Collectors.toMap with null entry values
- NullPointerException in Java with no StackTrace
- NullPointerException in Junit 5 MockBean
- Number of days between two dates in Joda-Time
- NullPointerException when trying to access views in a Kotlin fragment
- Numpy is installed but still getting error
- Number of lines in a file in Java
- object kafka is not a member of package org.apache
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData 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.