Sujith Sujith - 4 months ago 13
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

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.