1

I have some code here

 String array[]=new String[5];
    for(int i=0;i<array.length;i++){
        array[i]= "item "+String.valueOf(i);
        i++;
    }

and this is log message what i got after application crash

java.lang.IndexOutOfBoundsException : Invalid array range: 5 to 5

Could you guys explain me why pls ? I just want to declare an array and use for loop to initialize array element, just dont know why my code didn't work . Thank you

2
  • 4
    You have two i++. Why? Commented Nov 19, 2017 at 7:35
  • oh thank you , my very stupid mistake Commented Nov 19, 2017 at 7:39

4 Answers 4

3

because key index More increases than index array in your loop .

String array[]=new String[5];
    for(int i=0;i<array.length;i++){
        array[i]= "item "+String.valueOf(i);

    }
Sign up to request clarification or add additional context in comments.

Comments

2

remove extra i++.. it already redundant except you have some purpose to do so.

String array[]=new String[5];
for(int i=0;i<array.length;i++){
        array[i]= "item "+String.valueOf(i);
        //i++; //remove this.. it already redundant except you have some purpose
}

its java.lang.IndexOutOfBoundsException : Invalid array range: 5 to 5 because of the counter already exceed size of your string which 5 only..

use ArrayList instead

Comments

2

Just do this:

String array[]=new String[5];
for(int i=0;i<array.length;i++){
    array[i]= "item "+String.valueOf(i);
}

That second i++ was causing your index out of bounds.

Comments

1

Don't increment the 'i' value twice, which is causing this issue.

String array[]=new String[5];
for(int i=0;i<array.length;i++){
        array[i]= "item "+String.valueOf(i);
        //i++; //remove this..
}

Instead of using Array[] you can you Collections such as ArrayList<String> or List<String>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.