Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array...

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21504
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question comes up pretty often on the forums -- please search these forum for previous topics about this exact question.

Henry
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or add this line:
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
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the above post would have cleared the doubt.
Just to add on..
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all for clearing this.

Preetha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic