Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

integer array  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code from John Meyer's SCJP5
--------------------------------------------------------
int[] a= {1,2,3,4 };
for( int n :a){

a[n]= 0 ;
}


for ( int i : a )
{
System.out.println(i);//prints 0 0 3 0
}

------------------------------------------------------

can anybody tell me why above code doesn't thrown an IndexOutOfBound exception at runtime, instead having an output of 0 0 3 0?

Thanks !
 
Sheriff
Posts: 9611
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Christina!

If you search the forum, then you will see that this question has been asked many times. Here's a link to one of them...
 
Christina Pong
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankit,
Thanks for the reply. Wow, isn't it tricky?
The output is so much different than what you thought it supposed to be. Gosh, it beats me.
Byt the way, Ankit, you are so cool. You seem know all the answers or sources to those tricky questions. Great to have a pal like you in this forum :-)

Christina
 
Ankit Garg
Sheriff
Posts: 9611
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the question is a genius creation...
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!