-1

I just started learning java. I use the Eclipse IDE and JDK 7. I just learnt about arrays and was trying to run this code:

public class Testproj {
    public static void main(String[] args){

        int[] values = new int[4];
        values[1] = 10;
        values[2] = 20;
        values[3] = 30;
        values[4] = 40;

        System.out.println(values[1]);
        System.out.println(values[2]);
        System.out.println(values[3]);
        System.out.println(values[4]);
    }
}

But I get this compile time error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Testproj.main(Testproj.java:8)

Why am I getting this error and how can I eliminate it?

Elben
  • 173
  • 1
  • 8
  • 1
    Did you even try to google what `ArrayIndexOutOfBoundsException` mean? From [documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html): "Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or **greater than or equal to the size of the array**." – Pshemo Jul 13 '14 at 13:04
  • 1
    Thank you very much. I forgot about that. I should have researched a little bit before asking. – Elben Jul 13 '14 at 13:50

2 Answers2

3

The first index in the array is 0.

values[0] = 10;
values[1] = 20;
values[2] = 30;
values[3] = 40;
Alex
  • 11,451
  • 6
  • 37
  • 52
1

Array indexes are 0 based. The first value in the array should be values[0] = 10;.

Brett Okken
  • 6,210
  • 1
  • 19
  • 25