3

Is it possible to avoid ArrayIndexOutOfBoundsException in this case ??

package com;

public class Hi {

    public static void main(String args[]) {

        String[] myFirstStringArray = new String[] { "String 1", "String 2",
                "String 3" };

        if (myFirstStringArray[3] != null) {
            System.out.println("Present");
        } else {
            System.out.println("Not Present");
        }

    }

}
  • 2
    it is always possible to avoid an ArrayIndexOutOfBoundsException, checking against `array.length` before accessing the array element – guido Jul 18 '13 at 12:06
  • 1
    What are you trying to achieve? – Diogo Moreira Jul 18 '13 at 12:06
  • 1
    Your array will *always* have length 3, so index 3 is *always* invalid. It's not clear what you're asking really, but while you keep using an array of length three and asking for index 3, the answer is no: you can't avoid an exception. – Jon Skeet Jul 18 '13 at 12:07
  • Are you from non-java background developer? its better to use exception handling... – Hariharan Jul 18 '13 at 12:17

3 Answers3

5

Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?

if (myIndex < myFirstStringArray.length) {
    System.out.println("Present");
} else {
    System.out.println("Not Present");
}
ssindelar
  • 2,743
  • 1
  • 13
  • 36
2

In arrays, they are measured differently than numbers. The first object inside an array is considered 0. So, in your if statement, instead of a 3, you just put a 2.

if (myFirstStringArray[3] != null) {
        System.out.println("Present");

to

 if (myFirstStringArray[2] != null) {
        System.out.println("Present");

Hope this helps! :)

user2277872
  • 2,896
  • 1
  • 18
  • 21
0

Your String array contains 3 elements and you are accessing array[3] i.e. 4th element as index in 0 based and so you get this error (Exception, anyway).

To avoid the ArrayIndexOutOfBoundsException use an index within specified index range. And always check whether your index is >= array.length.

zEro
  • 1,236
  • 13
  • 24
Sachin Verma
  • 3,334
  • 9
  • 31
  • 66