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
2
u/awidesky Oct 24 '26
I can't think of any better(or cleaner) way to filter non-null objects(other than the stream).
If it isn't a miscommunication with the professor, maybe the prof wanted to say "there shouldn't be a null in the collection in the first place"
If your books array supposed to hold actual meaningful Book objects, you should make sure a null will never be put in the array.
A colleague of yours accidentally forgot about null and wrote a code without a null check, and your application will crash.
Every operation(printing names of the books, modifying the price of a particular book, calculating sums of prices or counting how may books there are, etc) needs to do a null check before do its job, and it's not only tedious work and bad design, but also a security risk.
"But how am I supposed to prevent null being put in the books array programmatically?"
That's called encapsulation, you'd learn if after you get familiar with class.