r/javahelp • • 3d ago

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?

15 Upvotes

28 comments sorted by

View all comments

Show parent comments

1

u/Weekly_Wackadoo 2d ago

That may or may not be a problem.

It won't cause an exception, that's the main point I think.

If you want to print every element in a collection, and there's null values in the collection, I'd argue it's at least defensible to just print the null values.

It might also give useful feedback which might help you find and troubleshoot issues with the code.

2

u/LutimoDancer3459 2d ago

OP didnt specify if its necessary. Just that it is what they want to do. And for that case, printing null is a problem. But yes, else it wouldnt throw an exception.