-1

In Java, I tried to change the value of a int (primitive type) array using the iterator. However, as you can see below, the iterator works fine when doing printing but it doesn't work to change the value of the int[]. While a simple for loop using index would do the job, I want to know why the for loop using iterator doesn't for changing value but does for printing. Thx

public class playGround {
        public static void main(String[] args) {
            int[] array = new int[5];
            System.out.println("using iterable: ---");
            for (int num : array) {
                System.out.print(" " + num);
                num = 2;
                System.out.println(" " + num);
            }

            System.out.println(" after: ---");
            for (int num : array) {
                System.out.print(" " + num);
            }
            System.out.println();
            System.out.println("using index: ---");
            for (int i = 0; i < array.length ; i++) {
                array[i] = i;
            }

            for (int num : array) {
                System.out.print(" " + num);
            }
        }
    }

output:

using iterable: ---
 0 2
 0 2
 0 2
 0 2
 0 2
 after: ---
 0 0 0 0 0
using index: ---
 0 1 2 3 4
Process finished with exit code 0
Luke
  • 145
  • 1
  • 2
  • 12

3 Answers3

2

You should check this out: How does the java for each loop work. However, if you want a deep explanation on the topic you should look at the Oracle Javadoc reference.

In any case, you are creating a copy of the values in a new variable named num. Therefore no modifications on the variable will be applied to the values in the array.

1

When you're modifying the elements in the forEach loop, you're actually modifying the value assigned by the iterator in int num, not the value of the original array. You're getting a literal, not a pointer to the object contained into the array.

Alex Roig
  • 1,534
  • 12
  • 18
0

int num is a local variable. Assigning the value 2 to it only changes it in the scope of a single for iteration.

Proper way to change the value of your primitive array is to access it on the heap like you have already done so with array[i] = i.

user2914191
  • 877
  • 1
  • 8
  • 21