programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 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
Sheriff
Posts: 23280
125

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.
According to The Precedence of the Java Operators
[] operator is one of the operator which has got the highest precedence.
= operator is one of the operator which has got the least precedence.

Preethi Dev
Ranch Hand
Posts: 265
Thanks to all for clearing this.

Preetha

 It is sorta covered in the JavaRanch Style Guide.