Results 1 to 3 of 3
  1. #1
    mew
    mew is offline Member
    Join Date
    Nov 2007
    Posts
    70
    Rep Power
    0

    Default java.lang.ArrayIndexOutOfBoundsException

    I am stuck. I have following code segment that is throwing
    java.lang.ArrayIndexOutOfBoundsException.

    Java Code:
    int []array = new int[10];
    
    for(int i=1;i<=10;i++)
    	array[i] = i;
    My array is of size 10. Where is the problem :confused:

  2. #2
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    Java Code:
    for(int i=1;i<=10;i++)
    	array[i] = i;
    Yes, your has a size of 10 elements. However, when you are iterating trough the array, you are telling it to get the 1st trough the 10 element. Arrays have a 0 index, meaning that the first element is not the element at 1, but the element at zero. So array[1] will in fact give you the second element present, while array[0] will output the first element. Likewise, array[10] is going to look for the 11th element, which you dont have, while array[9] is going to give you the last element.

  3. #3
    mew
    mew is offline Member
    Join Date
    Nov 2007
    Posts
    70
    Rep Power
    0

    Default

    Thanks staykovmarin for the explanation.
    Indexes in Java start from 0 as in C++.
    Thanks once again.

Similar Threads

  1. Replies: 8
    Last Post: 03-05-2011, 04:53 AM
  2. java.lang.ArrayIndexOutOfBoundsException
    By riccian in forum New To Java
    Replies: 0
    Last Post: 03-18-2008, 10:38 AM
  3. Replies: 1
    Last Post: 08-01-2007, 12:47 AM
  4. Replies: 1
    Last Post: 07-25-2007, 11:55 PM
  5. java.lang.ArrayIndexOutOfBoundsException
    By Marcus in forum New To Java
    Replies: 1
    Last Post: 07-05-2007, 06:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •