Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Each Loop Modification with Primitives

Tags:

java

for-loop

int arr[] = {0,1,2,3,4,5};
for (int i : arr){
    i = 1;
}

(Question 1): Why does this code segment not produce an error since it is using a for-each loop to modify elements?

 int arr[] = {0,1,2,3,4,5};
  for (int i : arr){
      arr[i] = 1; 
  }

(Question 2): How does this code work even though the for each-loop is not being used properly. Nonetheless, somehow all the elements are set to 1?

Thank you for your help.

like image 637
user9249390 Avatar asked Apr 21 '26 11:04

user9249390


1 Answers

(Question 1): Why does this code segment not produce an error since it is using a for-each loop to modify elements?

It doesn't modify elements. What it does is modify the variable i, which at any point in time happens to contain a copy of one of the elements, but is otherwise completely unrelated to the array.

(Question 2): How does this code work even though the for each-loop is not being used properly.

The loop may indeed look peculiar, but there's nothing fundamentally wrong with it. It is equivalent to the following code:

arr[0] = 1;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 1;
arr[5] = 1;

Of course this only works because arr happens to contain valid indices into itself. If it didn't (for example, if arr[0]=6), you'd get an ArrayIndexOutOfBoundsException.

like image 170
NPE Avatar answered Apr 24 '26 00:04

NPE