-1

Possible Duplicate:
ArrayIndexOutOfBoundsException

How do I prevent the following message from showing:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Test.main (Test.java:28 )

While compiling this code:

int [ ] a = { 2, 7, 8, 9, 11, 16 };  
for ( int i = 0; i <= a.length; i++ ) 
      System.out.println( a[i] ); // line 28 of class Test.java
Community
  • 1
  • 1
Jannne Newson
  • 103
  • 1
  • 2

2 Answers2

4

try

for ( int i = 0; i <a.length; i++ ) 
  System.out.println( a[i] ); // line 28 of class Test.java

Array indexes are zero based. i.e., Array indexes start from 0 to ArrayLength-1

in your case to access the last index of an array, you have to do a[a.length-1]. thus your loop condition should be i<a.length

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

The last index in your array is a.length - 1 so, you can use:

for (int i = 0; i < a.length; i++)
Reimeus
  • 158,255
  • 15
  • 216
  • 276