Дмитрий Б
Дмитрий Б

Reputation: 69

Java enhanced loop

Please, explain me step by step output of this code:

public class My {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,1};
        for (int n : a) {
            a[n] = 0;
        }
        for (int n : a) {
            System.out.println(n);
        }
    }
}

I know that is an enhanced loop. But do not understand how it works with a[n]=0 Why this code outputs 00301?

Upvotes: 2

Views: 176

Answers (3)

Sameersharma9
Sameersharma9

Reputation: 500

While iterating over the array a[], it changes the value of array. This is why a[2] and a[4] is never changed.

Upvotes: 0

Sanjeev Guglani
Sanjeev Guglani

Reputation: 2474

This code is actually replacing value of nth index where n is the value assign to n while traversing

Upvotes: 0

jsheeran
jsheeran

Reputation: 3037

You can debug this by adding a println statement:

    for (int n : a) {
        System.out.println("Changing element " + n + " of array from " + a[n] + " to 0");
        a[n] = 0;
    }

The output of this is:

Changing element 1 of array from 2 to 0
Changing element 0 of array from 1 to 0
Changing element 3 of array from 4 to 0
Changing element 0 of array from 0 to 0
Changing element 1 of array from 0 to 0

Upvotes: 3

Related Questions