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)