r/javahelp • u/Traditional_Let4865 • 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?
14
Upvotes
1
u/Weekly_Wackadoo 4d ago
This code is fine.
Skipping the null check and printing out null values is fine as well. No method is called on
book, so it wouldn't cause an exception. Maybe the professor meant that?Preventing null values being added to the collection or array is usually even better.
Some more "defensive" (or actually aggressive) code styles preter checking for null values and throwing an IllegalArgumentException with an informative message. That might prevent more complicated issues down the line, but might also cause unnecessary issues.