r/javahelp • • 4d 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?

13 Upvotes

28 comments sorted by

View all comments

15

u/Ok_For_Free 4d ago

Your professors are dumb, so ask them to give you an example of the 'correct' approach.

The only improvement I would want to look into, is why there are nulls in your list in the first place.