Win a copy of Learn Spring Security (video course) this week in the Spring forum!

Array...

Preethi Dev
Ranch Hand
Posts: 265
Hi , i got it from Inquisition.

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

output:0030

could someone explain me the logic behind this?
i thought the answer would be 0000.

Thanks
Preetha

Henry Wong
author
Marshal
Posts: 20880
75

Henry

Punit Singh
Ranch Hand
Posts: 952
see it is simple.

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

int i:arr // {1,2,3,4}---> that is 1
arr[1]=0; //arr={1,0,3,4}

int i:arr // {1,0,3,4}--->that is 0
arr[0]=0; //arr={0,0,3,4}

int i:arr // {0,0,3,4}--->that is 1
arr[3]=0; //{0,0,3,0}

int i:arr // {0,0,3,0} that is 1
arr[0]=0; //arr={0,0,3,0}

so finally arr={0,0,3,0}

patrick avery
Ranch Hand
Posts: 46
System.out.println("i = " + i + " arr = " + Arrays.toString(arr));

after this line:
arr[i]=0;

to watch the loop in progress:
i = 1 arr = [1, 0, 3, 4]
i = 0 arr = [0, 0, 3, 4]
i = 3 arr = [0, 0, 3, 0]
i = 0 arr = [0, 0, 3, 0]

James Tharakan
Ranch Hand
Posts: 580
I think the above post would have cleared the doubt.