Search code examples
javaarraysindexoutofboundsexception

Check last array element


I've got a string array, and I should check i element and i + 1, for some coincidence, except the last element, because it allready checked by previous element.

String[] somearr = new {"first, second"};

arr[i] && arr[i+1], allready checked the last element, and when arr[i] = second I've got ArrayIndexOutOfBoundsException.

if (arr[i].equals("first") && arr[i + 1].equals("second"){
//do something;
} 

My question is how not to check the last element because I allready checked it in previous?


Solution

  • Check if index + 1 out of bound:

    if ((index + 1) < somearr.length && somearr[index].equals("first") && somearr[index + 1].equals("second")) {
        // do something
    }