1

Can someone explain to me why when I rearrange the conditions in the following if statement it either throws a StringIndexOutOfBoundsException or it does not;

public int matchUp(String[] a, String[] b) {
int count = 0;

for (int i = 0; i < a.length; i++) {
  if (a[i].length() > 0 && b[i].length() > 0 &&
      a[i].charAt(0) == b[i].charAt(0)) {
      count++;
  }
}
   return count;
}

Basically my question is, how is this if statement

if (a[i].charAt(0) == b[i].charAt(0) &&
    a[i].length() > 0 && b[i].length() > 0)

different from this if statement

if (a[i].length() > 0 && b[i].length() > 0 &&
    a[i].charAt(0) == b[i].charAt(0)) {
      count++;
}

The first one throws an exception, for example:

matchUp(["", "", "ccc"], ["aa", "bb", "cc"]) → 1    

Exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (line number:6)
fabian
  • 80,457
  • 12
  • 86
  • 114

1 Answers1

0
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (line number:6)

means that you tried to access index 0 of an array which is empty.

Another thing is, that expression expression1 && expression2 is evaluated to false when only expression1 is false. There is no attempt to evaluate expression2.

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • This is true, but it doesn't really allude to how the order of the operands matter when `&&` is evaluated. – byxor Dec 13 '16 at 18:17