for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are based on indexes 0. This means that your first element must be available with index 0 and, obviously, the last one along the length of your array minus 1.
int tab[] = new int[3];
Here you access the last element by calling tab[2] or tab[tab.length-1] , which is equivalent.
Apologies, it was just a mistake in the code that I put in the question.
The problem is what you have to do: System.out.print(i + ", "); You should read this and this about loop reinforcement.
The for statement also has a different form for iterating through Collections and Arrays. This form is sometimes called advanced for the statement, and can be used to make your loops compact and easy to read. To demonstrate, consider the following array, which contains numbers from 1 to 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program EnhancedForDemo uses advanced to loop through an array:
class EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } }
In this example, the variable element contains the current value from an array of numbers .
So item contains the current value from an array of numbers and not the current index. That's why you get IOOBE .