Java for-each loop throw NullPointException
for-loop, java, loops
Solution
I see the following reasons, although I have no idea if anybody thought about this, when it was implemented, and what the actual reasons were.
As you demonstrated the current behavior of the for(:)-loop is very easy to understand. The other behavior isn't
It would be the only thing in the java universe behaving in this way.
It wouldn't be equivalent to the simple for-loop so migrating between the two would actually not be equivalent
Using null is a bad habit anyway, so NPEs are a nice way of telling the developer "you F***ed up, clean up your mess" with the proposed behavior the problem would just be hidden.
What if you want to do anything else with the array before or after the loop ... now you would have the null check twice in your code.
Problem
The following java segment will result a NullPointException, since the variable list is null, which is pass to the for-each loop. ``` List<> arr = null; for (Object o : arr) { System.out.println("ln "+o); } ``` I think `for (Object o : arr){ }` is a equivalent to `for (int i = 0; i < arr.length; i++) { }` and/or ``` for (Iterator<type> iter = arr.iterator(); iter.hasNext(); ){ type var = iter.next(); } ``` In either cases arr is null will cause arr.length or arr.iterator() throws a NullPointException I'm just curious the reason why `for (Object o : arr){ }` is NOT translate to ``` if (arr!=null){ for (int i = 0; i < arr.length; i++) { } } and if (arr!=null){ for (Iterator<type> iter = arr.iterator(); iter.hasNext(); ){ type var = iter.next(); } } ``` Include arr!=null expression could reduce code nesting.