Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java 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: 9613
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: 9613
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...
 
moose poop looks like football shaped elk poop. About the size of this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!