1

public class Main {

public static void main(String[] args) {

    int[] numbers = {1, 2, 3}; // it gives me arrayindexoutofboundexception

    int length = numbers[3];

    char[] chars = new char[length];

    chars[numbers.length + 4] = 'y';

    System.out.println("Done!");
}

}

How to remove array index out of bound exception .

2 Answers2

4

Don't access numbers[3]; when your array has only 3 elements, whose indices are 0, 1 and 2.

Also don't access chars[numbers.length + 4] before making sure this is a valid index of the chars array.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks a lot, it helped. what if i try to catch the exception,then it get compiled without exception but there is no output,can you explain,thanks? – Kedar Kholiya Dec 23 '14 at 13:09
  • @KedarKholiya Don't catch the exception. You should avoid it in the first place. – Eran Dec 23 '14 at 13:19
0

Change:

int length = numbers[3]; 

To:

int length = numbers[2];