All Tools

Debugging & Unit Testing Explorer

Find hidden bugs in Java code snippets, write test cases that catch buggy implementations, and browse common error patterns with side-by-side fixes.

001 / 7

Sum Array Elements

EasyOff-by-One

Click on the line you think contains the bug, then press Reveal Answer.

1public static int sumArray(int[] arr) {
2 int sum = 0;
3 for (int i = 0; i <= arr.length; i++) {
4 sum += arr[i];
5 }
6 return sum;
7}

Reference Guide

Common Runtime Errors

Runtime errors crash your program while it runs. The most frequent ones in Java are NullPointerException (calling a method on null), ArrayIndexOutOfBoundsException (accessing invalid indices), and StackOverflowError (infinite recursion).

To prevent them, check for null before dereferencing, validate array indices against length, and always include a base case in recursive methods.

Off-By-One Errors

Off-by-one errors happen when loop bounds are wrong by exactly one. Typical causes include using <= instead of < with array length, starting a loop at 1 instead of 0, or forgetting that the last valid index is length - 1.

A reliable habit is to mentally trace the first and last iterations to verify the boundary values before running.

Writing Good Test Cases

Good tests cover typical cases, edge cases, and boundary conditions. For a method that searches an array, test with the target at the beginning, middle, end, and not present at all. Also test with a single-element array and an empty array.

A strong test suite should pass on the correct implementation and fail on a buggy one. If all your tests pass on both, your tests are too weak.

== vs .equals()

In Java, == compares object references (memory addresses), while .equals() compares values. Two String objects created with new String("hello") are different objects but have equal content.

Always use .equals() for String comparison. The only time == works reliably on Strings is with literal values due to the String pool, but relying on this is fragile and error-prone.