You assign a new object to an array element (which is a variable that will be a reference to the object), which can be accessed outside the for loop.
Object[] objs = new Object[10]; for (int i=0;i<objs.length;i++) objs[i] = new Object();
But for each loop, you assign a new object to a local variable (and not to the elements of the array)
Object[] objs = new Object[10]; for (Object obj : objs){ obj = new Object(); }
and if we talk about this line
for (Object obj : objs){
Then this means that you take the value of the objs element into the local variable obj, which is null.
source share