-3
import java.io.*;

public class Array {

    public static void main(String args[]) {

        int i = 0;
        int add = 0;

        int a[] = {4, 1, 1, -6};

        for (i = 0; i < a.length; i++) {
            add = add + a[i];

            if (add - a[i + 1] == 0) {
                System.out.println("exist");

            }
        }

    }
}

I am getting as below error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Arraylist1.main(Arraylist1.java:21)
Tom
  • 16,842
  • 17
  • 45
  • 54
Sainath Pawar
  • 65
  • 2
  • 3
  • 10
  • in end of for i equal a.length, so, you has not a[i+1] element. – M2E67 Apr 09 '17 at 08:27
  • And hint: you want us to spend our time to help you. So you please spend the 1 minute it takes to properly format/indent all of your input. That **preview** section close to the edit window, and all the helpful explanations there ... are there for a reason! – GhostCat Apr 09 '17 at 08:28

1 Answers1

1

Because you are already increment your index in :

if (add - a[i + 1] == 0) {
//----------^---^

To solve your problem you have to iterate until a.length - 1 instead of a.length, because the last index is 3 so when you try to get a[3+1] it will throw ArrayIndexOutOfBoundsException exception because this index is not exit

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140