r/javahelp • u/Traditional_Let4865 • Oct 23 '26
Iterating over null objects in an array
So I'm making a program that iterates over an array of Book objects and I made a for loop to print them all out. I want it to skip over any reference to a null object in the array so I've written:
for (Book book : books) {
if(book != null){
System.out.println(book);
}
}but I've had professors tell me I shouldn't write "book != null" to avoid printing the null values. the code works just fine and is relatively simple and easy to read, just wondering what most programmers use to navigate this?
13
Upvotes
View all comments
3
u/olddev-jobhunt Oct 23 '26
It's relatively easy to read... relatively. The thing is, your loop isn't going to just be printing things. It'll be doing things too! So you're mixing selection logic (the null check) with the domain logic (the operation you're doing.) That's not a problem necessarily, but it's something to watch out for.
Imagine you later decide that the loop contents are complex enough to be pulled out into a function, which you can then call on a single book or use in a loop for multiple.
Anyway, for me I'd probably just avoid nulls in the list in the first place, or maybe filter in the for loop parameter rather than within the loop.