This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array..." Watch "Array..." New topic
Author

Array...

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
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

Joined: Sep 28, 2004
Posts: 18754
    
  40

This question comes up pretty often on the forums -- please search these forum for previous topics about this exact question.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
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}


SCJP 6
patrick avery
Ranch Hand

Joined: Sep 12, 2008
Posts: 46
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]


SCJA 96%
SCJP 6 88%
skipping SCJD to work on passing SCWCD
James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

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.


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Thanks to all for clearing this.

Preetha
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Array...