1

I got this error. Though it may be very basic. I have declared array of length 3. Why does it still show an OutofBoundException error ?

    public static void main(String[] args) {
            int i;
            String[] arr = new String[3];
            Scanner input = new Scanner(System.in);
            System.out.println("Please enter the name");
            for (i = 0; i < 3; i++) {
                arr[i] = input.nextLine();
            }
            System.out.println(arr[i]);
        }
   Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
        at arraysPractice.Arr2.main(Arr2.java:21)
Magneto
  • 17
  • 5

3 Answers3

3

It's because after completion of for loop, your i will be 3. Which is outOfBound because your array size is 3 only.

so print

System.out.println(arr[i-1]);

if you want to print last element.

NOTE

To avoid this type of errors, try using arr[arr.lenght - 1] to print last element.

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
  • you can accept the answer by pressing small right below voting button, if it solved your problem. :) @user2863083 – Kaushal28 Dec 29 '16 at 09:55
0

The loop is terminated with i having the value of 3. You then try to print arr[i], which won't work, since it only has the indexes 0, 1 and 2.

I'm guessing you meant to have the System.out.println statement inside the loop instead of after it?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

first iteration). I=0 and 0<3 so it goes into for loop and after that I++ so I=1.
second iteration).I=1 and 1<3 so it goes into for loop and after that I++ so I=2.
third iteration)I=2 and 2<3 so it goes into for loop and after that I++ so I=3
fourth iteration)I=3 and 3<3(false) it will exit loop and after that u are you are trying to print. System.out.println(arr[i]);where I=3. and your array size=3(means max position can be 2 and remaining positions are (0,1,2)) so it is index out of bound as you want to check array with index 3 but array max index is 2.

So QUICK fix put System.out.println(arr[i]); in for loop.