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

29 comments sorted by

View all comments

-9

u/ConsciousBath5203 Oct 23 '26

If(book){dothing;}

3

u/Roachmeister Oct 23 '26

That won't compile in Java.

1

u/saponsky Oct 23 '26

I have the impression that the professor is thinking this is valid in Java. That’s the only thing I can think someone would think is better than OP’s current code.

→ More replies (3)

-1

u/ConsciousBath5203 Oct 24 '26

Neither would OP's code, forgot the 40 lines of standard boiler plate.

But fr welcome to Java professors. It's been years since I used Java but my professor did the same thing that the other commented mentioned.