how to fix Index 2 out of bounds for length 2 when looping through an array in java

Java
1
2
3
for (int i = 0; i < a.length; i++) { // GOOD
  sum += a[i];
}

Source

Also in Java: