Java Modifying Elements in a foreach

You can’t do that in a foreach loop.

for (int i=0; i<copyArray.length;i++)
    copyArray[i] /= 2;

Else you are not assigning it back into the array. Integer objects are immutable by the way so can’t modify them (creating new ones though).

Updated from comment:
Beware though that there are a few things going on, autoboxing/unboxing for example, roughly:

copyArray[i] = Integer.valueOf(copyArray[i].intValue()/2);

Leave a Comment