Sujith Sujith - 1 year ago 79
Java Question

Why enhanced for loop is not performing the null checking

Why the enhanced for loop is not performing null checking before iterating over the collection.

Answer Source

If you mean that this would go bang:

int[] array = null;
for (int x : array) {

... then I think it's entirely proper for that to throw a NullPointerException. The alternative would be for it to silently swallow the null, and treat that as equivalent to an empty array. That's not the approach Java takes anywhere else - why should this be different? It would make the language inconsistent.

The one place I wish there were more handling (but explicit handling) is switching on an enum - it would be nice to be able to provide a case for null, to avoid checking for that one special value beforehand. But that's a very different construct, which is specifically trying to take different actions for different values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download