aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enhanced for Loop Vs for Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Enhanced for Loop Vs for Loop" Watch "Enhanced for Loop Vs for Loop" New topic
Author

Enhanced for Loop Vs for Loop

Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643

in above code i am trying to overwrite each element of array by 0
First i overwrite each element of forArr[] array by 0 using for loop
it gives out 0 0 0 0 so it is ok.
But when i try to overwrite each element of enhancedForArr[] by 0
using enhanced for loop it gives output 0 0 3 0

i am not able to understand why.

Thanks
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

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


  • i = 1 (because enhancedForArr[0]=1) then setting enhancedForArr[1]=0.
  • i = 0 (because enhancedForArr[1]=0) then setting enhancedForArr[0]=0.
  • i = 3 (because enhancedForArr[2]=3) then setting enhancedForArr[3]=0.
  • i = 0 (because enhancedForArr[3]=0) then setting enhancedForArr[0]=0.

  • then you have 0,0,3,0
    xu yin
    Greenhorn

    Joined: Aug 11, 2006
    Posts: 2
    The explanation by wise owen is clear.
    Because you overwrite the data "2" before you get it.
    If you use "int []enhancedForArr = {0,1,2,3};",
    you will get what you want.

    Hope I help you partly.
    vidya sagar
    Ranch Hand

    Joined: Mar 02, 2005
    Posts: 580
    Really Interesting
    Ty Oftrans
    Greenhorn

    Joined: Dec 14, 2005
    Posts: 7
    This really is interesting! I am just now trying to understand this very issue (the 'deep' differences between for and enhanced for - if there are any) and this exercise brought out something interesting that would have escaped my attention and understanding.
    Thanks for the exercise and for Wise's explanation!

    Ty
     
    I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
     
    subject: Enhanced for Loop Vs for Loop
     
    Similar Threads
    Colon : in for{} loop?
    Enums and operators
    John Meyer's SCJP 5 mock exam doubt
    queries
    Enhanced For Loop Problem