Java: Array Index Out of Bounds Exception

You should use < and not <= in:

for (int i = 0; i <= newArray.length; i++)
                  ^^

If foo any array, valid index of foo are [0,foo.length-1]

Using foo.length as an index will cause ArrayIndexOutofBoundsException.

And also lArray which contains number of natural numbers <=x but excluding only one number 1, its value should be x-1 and not x-2.

Leave a Comment