-1

when write the statement to tell the program to break or return, the if statement still executes every time when the condition is not satisfied and cause error :java.lang.ArrayIndexOutOfBoundsException

I've tried greater than and equal ==, both worked. And I checked ">" is also an operator in java. Then why it still executes?

public class adjacentElementsProduct {

    static int adjacentElementsProduct(int[] inputArray) {
    if(inputArray ==null|| inputArray.length<0) return 0;
    int res=Integer.MIN_VALUE;

    for( int i=0; i<inputArray.length;i++){
       int stop=i+1;

       if((i+1) > inputArray.length) break;

       res=Math.max(res,inputArray[i]*inputArray[i+1]);
    }
    return res;
}

'''

In this case, since '''if((i+1) > inputArray.length) break;''' doesn't work, so the error message is: java.lang.ArrayIndexOutOfBoundsException

Rio Chen
  • 1
  • 6
  • even if `(i+1)==inputArray.length`, you would get that exception. The highest index you access in an array is `inputArray.length-1`. – f1sh Jul 24 '19 at 21:22
  • What is max value `i` can take based on `i inputArray.length) break;` will never be true so you will not execute `break;`. Think it over again, and do you really need that breaking condition? If you want to iterate one time less change `i – Pshemo Jul 24 '19 at 21:28
  • pls upvote once for me, my question point is not at the "OfBoundsException", it's in how it works in if((i+1) > inputArray.length) break; I went through the link that he marked mine as duplicated, it didn't answer my question, that's not my question. – Rio Chen Jul 26 '19 at 15:29

1 Answers1

0

Java arrays have zero-based indexing, so the last element in an array of length N is at the (N-1)th element.

EX: int[] a = {1, 2, 3}, to access the element 3, we would write a[2] or a[a.length - 1].

In your case, your loop will go to i = inputArray.length - 1, so if you call inputArray[i + 1] you are calling inputArray[inputArray.length] which is out of bounds. To avoid this, you can either modify the loop end condition to i < inputArray.length - 1 or you can change your if statement to be

if((i+1) >= inputArray.length) break;.

Mihir Kekkar
  • 528
  • 3
  • 10