Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Enhanced For Loop

 
Krishna doddi
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain me with an example how Enhanced For loop works. I tought I understood it well until I came accross this question


Ans : 0300

I tought there be a Runtime ArrayIndexOutOfBound Exception

Thanks
Siddharth


[HENRY: Added code tags]
[ October 26, 2006: Message edited by: Henry Wong ]
 
Henry Wong
author
Marshal
Pie
Posts: 21395
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The enhanced for loop will go through the array an set i to each member of the array.

1. On the first iteration, i will be 1, and set arr[1] to 0.
2. On the second iteration, i will be 0 (see step 1), and set arr[0] to 0.
3. On the third iteration, i will be 3, and set arr[3] to 0.
4. On the last iteration, i will be 0 (see step 3), and set arr[0] to 0.

So... final result should be 0030.

Henry
 
Krishna doddi
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry,

Your explanation and a Pen and a Paper helped me.

Thanks,
Siddharth
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic