Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

probleme in (arrayindexoutofboundexcep)  RSS feed

 
jaysingh solanki
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code:
class Pass
{

public static void main(String arg[])
{ int arr[]={1,2,3,4,5};
arr[0]=arr[3];
for (int i=0;i<arr.length;i++)
System.out.println(arr[5]);//line 1
}
}
My auestion is:
when i compile the programe
it compile ,but gives error
in winNT that application error
is occure.you dont think it
should give ArrayIOOBExcep.
If i change line one arr[4] than it print 5 five times;
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Beginner's forum...
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not exactly sure what your question is, but I'll guess it has to do with being surprised that arr[5] causes an ArrayIndexOutOfBoundsException at runtime when used on an array with a size of 5. Well...
In Java, the first component of an array is at index 0, the second component is at index 1... and the fifth component is at index 4. So, dereferencing the array at index 5 is actually trying to access the sixth component in the array, but the array only has five components. This isn't a condition that the Java compiler attempts to check at compile time. Thus the runtime error.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!