Skip to lesson

Finding, Explaining and Preventing the Bug

In a find-the-bug round the interviewer shows a short method that "sometimes gives the wrong answer" and watches how you think. They are checking for a calm method, a clear fix, and an explanation of the cause and the test that proves it.

A method for reading unfamiliar code

An edge case is an input at the boundary of what a method accepts, such as an empty array, one item, zero, a negative number, null or the largest value. Most bugs hide there.

The program runs a method that finds the biggest mark on a normal input, then on inputs with duplicates and with all-negative values.

Example 1 · Edge cases expose a wrong starting value

SecondLargestDemo.javaJava
public class SecondLargestDemo {    static int secondLargestBuggy(int[] a) {        int max = 0, second = 0;        for (int x : a) {            if (x > max) {                second = max;                max = x;            } else if (x > second) {                second = x;            }        }        return second;    }
    static int secondLargest(int[] a) {        int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;        for (int x : a) {            if (x > max) {                second = max;                max = x;            } else if (x > second && x != max) {                second = x;            }        }        return second;    }
    static void check(String name, int[] input, int expected) {        System.out.println(name + ": expected " + expected                + ", buggy " + secondLargestBuggy(input)                + ", fixed " + secondLargest(input));    }
    public static void main(String[] args) {        check("normal", new int[] {3, 9, 7}, 7);        check("duplicates", new int[] {9, 9, 7}, 7);        check("all negative", new int[] {-5, -2, -9}, -5);    }}
Output
normal: expected 7, buggy 7, fixed 7
duplicates: expected 7, buggy 9, fixed 7
all negative: expected -5, buggy 0, fixed -5

What this code does

  • The normal case passes, which is why the bug survives casual testing. Duplicates and all-negative input expose two separate bugs.
  • Fixes: start from Integer.MIN_VALUE instead of 0, and skip values equal to the current max.

Read the contract first: what goes in, what should come out, and what the name promises. Then trace one small normal input, attack it with edge cases, and say aloud what you are doing. Where to look:

  • Contract: inputs, output and the promises in the name and comments.
  • Normal case: trace one small input from start to end.
  • Edge cases: empty, one item, duplicates, negatives, zero, null, max values.
  • Hot spots: loop bounds, starting values, ==, a missing break, arithmetic on large ints.

Revise: A bug-hunting routine (opens in a new tab).

Order of execution

The find-the-bug routine

Tap the steps in the order a strong candidate does them.

Classic bugs: the short list to check every time

An off-by-one error is a loop or index that goes one step too far or stops one step too early, such as i <= a.length where i < a.length was meant.

Two programs show the classic bugs as a buggy method next to its fix: loop bounds, a missing break, == on Strings, a null and an int overflow.

Example 2 · Off-by-one and wrong loop bounds

LoopBoundDemo.javaJava
public class LoopBoundDemo {    static int sumFirstNBuggy(int n) {        int s = 0;        for (int i = 1; i < n; i++) s += i;     // misses n itself        return s;    }
    static int sumFirstN(int n) {        int s = 0;        for (int i = 1; i <= n; i++) s += i;        return s;    }
    static int maxMarkBuggy(int[] marks) {        int best = marks[0];        for (int i = 1; i <= marks.length; i++) best = Math.max(best, marks[i]);        return best;    }
    static int maxMark(int[] marks) {        int best = marks[0];        for (int i = 1; i < marks.length; i++) best = Math.max(best, marks[i]);        return best;    }
    static int countVowelsBuggy(String s) {        int c = 0;        for (int i = 0; i < s.length() - 1; i++) if ("aeiou".indexOf(s.charAt(i)) >= 0) c++;        return c;    }
    static int countVowels(String s) {        int c = 0;        for (int i = 0; i < s.length(); i++) if ("aeiou".indexOf(s.charAt(i)) >= 0) c++;        return c;    }
    public static void main(String[] args) {        System.out.println("sumFirstN(5): buggy " + sumFirstNBuggy(5) + ", fixed " + sumFirstN(5));        int[] marks = {78, 92, 65};        try {            maxMarkBuggy(marks);        } catch (ArrayIndexOutOfBoundsException e) {            System.out.println("maxMark: buggy " + e.getClass().getSimpleName() + ", fixed " + maxMark(marks));        }        System.out.println("countVowels(\"india\"): buggy " + countVowelsBuggy("india") + ", fixed " + countVowels("india"));    }}
Output
sumFirstN(5): buggy 10, fixed 15
maxMark: buggy ArrayIndexOutOfBoundsException, fixed 92
countVowels("india"): buggy 2, fixed 3

What this code does

  • Three faces of the same bug: a bound one too small (i < n), one too large (i <= length), and an extra - 1 that skips the last character.
  • Test the first and last positions explicitly: "india" ends in a vowel, which is what exposed the third bug.

Example 3 · Missing break, == on Strings, null and overflow

ClassicBugsDemo.javaJava
import java.util.Objects;
public class ClassicBugsDemo {    static String gradeBuggy(char g) {        String r = "";        switch (g) {            case 'A': r += "Excellent ";            case 'B': r += "Good ";            default:  r += "Keep going";        }        return r;    }
    static String grade(char g) {        return switch (g) {            case 'A' -> "Excellent";            case 'B' -> "Good";            default -> "Keep going";        };    }
    static boolean isAdminBuggy(String role) { return role == "admin"; }    static boolean isAdmin(String role) { return "admin".equals(role); }
    static String greetBuggy(String name) { return "Hi " + name.toUpperCase(); }    static String greet(String name) { return "Hi " + Objects.requireNonNullElse(name, "guest").toUpperCase(); }
    static int averageBuggy(int a, int b) { return (a + b) / 2; }    static int average(int a, int b) { return (int) (((long) a + b) / 2); }
    public static void main(String[] args) {        System.out.println("grade('A'): buggy [" + gradeBuggy('A') + "], fixed [" + grade('A') + "]");        String role = new String("admin");        System.out.println("isAdmin: buggy " + isAdminBuggy(role) + ", fixed " + isAdmin(role));        try {            greetBuggy(null);        } catch (NullPointerException e) {            System.out.println("greet(null): buggy NullPointerException, fixed " + greet(null));        }        int big = 2_000_000_000;        System.out.println("average: buggy " + averageBuggy(big, big) + ", fixed " + average(big, big));    }}
Output
grade('A'): buggy [Excellent Good Keep going], fixed [Excellent]
isAdmin: buggy false, fixed true
greet(null): buggy NullPointerException, fixed Hi GUEST
average: buggy -147483648, fixed 2000000000

What this code does

  • Without break, case 'A' falls through into 'B' and default. The arrow switch (Java 14+) has no fall-through at all.
  • role was built at runtime, so == is false. requireNonNullElse (Java 9+) supplies a default for null, and doing the sum in long avoids the overflow.

These bugs cover most interview questions. Scan for each one, in this order:

  • Off-by-one or wrong loop bound: i < n against i <= n, a loop that skips the first or last item or runs one step past the end.
  • Missing break: an old-style switch falls through into the next case.
  • == on Strings or wrappers: it compares objects, not values.
  • NullPointerException: a method called on something that can be null.
  • Integer overflow: sums and products wrap silently.
  • Wrong starting value: max = 0 fails for all-negative data.

Revise: String equals vs == (opens in a new tab).

Find the bug

Find the bug

Tap the line that causes the wrong result.

findMax returns 0 for the marks -4, -1 and -7.

Round 1 of 4

Explaining the fix aloud: cause, fix, test

The root cause is the real reason a bug happens, such as a wrong loop bound, as opposed to the symptom you see, such as an exception. A good fix removes the cause, not the symptom.

The program shows a palindrome check that fails, then prints the cause, the fix and the tests that prove it.

Example 4 · Cause, fix and the tests that prove it

PalindromeFixDemo.javaJava
public class PalindromeFixDemo {    static boolean isPalindromeBuggy(String s) {        int n = s.length();        for (int i = 0; i < n / 2; i++) {            if (s.charAt(i) != s.charAt(n - i)) return false;   // bug: n - i        }        return true;    }
    static boolean isPalindrome(String s) {        int n = s.length();        for (int i = 0; i < n / 2; i++) {            if (s.charAt(i) != s.charAt(n - 1 - i)) return false;        }        return true;    }
    public static void main(String[] args) {        try {            isPalindromeBuggy("madam");        } catch (StringIndexOutOfBoundsException e) {            System.out.println("Cause: at i = 0 the buggy code reads index 5 of a 5-letter word");        }        System.out.println("Fix: compare s.charAt(i) with s.charAt(n - 1 - i)");        String[] tests = {"madam", "abba", "a", "", "ab"};        StringBuilder results = new StringBuilder("Tests:");        for (String t : tests) {            results.append(" \"").append(t).append("\"=").append(isPalindrome(t));        }        System.out.println(results);    }}
Output
Cause: at i = 0 the buggy code reads index 5 of a 5-letter word
Fix: compare s.charAt(i) with s.charAt(n - 1 - i)
Tests: "madam"=true "abba"=true "a"=true ""=true "ab"=false

What this code does

  • The answer follows cause → fix → tests. The tests cover odd and even lengths, the one-letter and empty edge cases, and one false case.
  • A fix with no test that would have failed before is only a guess; say which test failed before and passes now.

Interviewers grade the explanation as much as the fix. Use three short parts: the cause ("when i is 0, charAt(n - i) reads one past the end"), the fix ("compare with n - 1 - i") and the test ("madam and abba return true, ab returns false, empty and one-letter words do not crash"). Wrapping the loop in try/catch would hide the crash but keep the wrong logic.

Revise: What to catch and what not (opens in a new tab).

Prevention: unit tests, static analysis, code review

A regression test is a test written for a bug that was fixed and kept in the test suite, so the bug cannot quietly return when the code changes later.

The program is a tiny test runner. It checks a midpoint method with small and huge numbers, fails on the buggy (a + b) / 2, and passes after the fix.

Example 5 · A tiny test runner catches the regression

MiniTestDemo.javaJava
import java.util.Objects;import java.util.function.IntBinaryOperator;
public class MiniTestDemo {    static int passed;    static int failed;
    static void assertEquals(String name, int expected, int actual) {        if (Objects.equals(expected, actual)) {            passed++;        } else {            failed++;            System.out.println("  FAIL " + name + ": expected " + expected + " but was " + actual);        }    }
    static void runTests(String label, IntBinaryOperator average) {        passed = 0;        failed = 0;        System.out.println(label);        assertEquals("small", 5, average.applyAsInt(4, 6));        assertEquals("negatives", -2, average.applyAsInt(-7, 2));        assertEquals("both large", 2_000_000_000, average.applyAsInt(2_000_000_000, 2_000_000_000));        assertEquals("opposite large", 0, average.applyAsInt(-2_000_000_000, 2_000_000_000));        System.out.println("  " + passed + " passed, " + failed + " failed");    }
    public static void main(String[] args) {        runTests("Buggy (a + b) / 2", (a, b) -> (a + b) / 2);        runTests("Fixed with long", (a, b) -> (int) (((long) a + b) / 2));    }}
Output
Buggy (a + b) / 2
  FAIL both large: expected 2000000000 but was -147483648
  3 passed, 1 failed
Fixed with long
  4 passed, 0 failed

What this code does

  • The edge-case tests stay in the project forever, so if someone "simplifies" the method back to (a + b) / 2, the large-value test fails at once.
  • In real projects these are JUnit tests run on every build; this single-file runner just shows the idea.

Prevention is the usual follow-up: "how would you stop this happening again?" Name a habit for the bug you just fixed:

  • Unit tests for the edge cases that broke, kept as regression tests.
  • Static analysis such as IntelliJ inspections, SpotBugs or SonarLint, which flag == on Strings and possible nulls.
  • Code review checklists: loop bounds, null handling, overflow, resources closed.
  • Safer features: arrow switch, Objects.equals, Math.addExact, long for sums.

Revise: Arrange, act, assert (opens in a new tab) and Static analysis with SonarLint (opens in a new tab).

Predict the output

Does the midpoint survive?

Read each program and pick what it prints.

Round 1 of 3

The buggy midpoint with huge numbers.

public class MidRound1 {
public static void main(String[] args) {
int low = 2_000_000_000;
int high = 2_100_000_000;
System.out.println((low + high) / 2);
}
}

Worked examples: five short buggy methods

Five more classic bugs sit side by side: counting the digits of 0, testing odd numbers, a factorial that overflows, a swap that changes only copies, and a reverse loop that starts one past the end.

Example 6 · Five more buggy methods, side by side

FiveBugsDemo.javaJava
public class FiveBugsDemo {    // 1. Count digits: the loop never runs for 0    static int digitsBuggy(int n) { int c = 0; while (n > 0) { n /= 10; c++; } return c; }    static int digits(int n) { n = Math.abs(n); int c = 1; while (n >= 10) { n /= 10; c++; } return c; }
    static boolean isOddBuggy(int n) { return n % 2 == 1; }    static boolean isOdd(int n) { return n % 2 != 0; }
    // 3. Factorial: 15! does not fit in int    static int factorialBuggy(int n) { int f = 1; for (int i = 2; i <= n; i++) f *= i; return f; }    static long factorial(int n) { long f = 1; for (int i = 2; i <= n; i++) f *= i; return f; }
    static void swapBuggy(int a, int b) { int t = a; a = b; b = t; }    static void swap(int[] arr, int i, int j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; }
    // 5. Reverse: starts one past the end    static String reverseBuggy(String s) {        StringBuilder sb = new StringBuilder();        for (int i = s.length(); i > 0; i--) sb.append(s.charAt(i));        return sb.toString();    }    static String reverse(String s) {        StringBuilder sb = new StringBuilder();        for (int i = s.length() - 1; i >= 0; i--) sb.append(s.charAt(i));        return sb.toString();    }
    public static void main(String[] args) {        System.out.println("1 digits(0):     buggy " + digitsBuggy(0) + ", fixed " + digits(0));        System.out.println("2 isOdd(-3):     buggy " + isOddBuggy(-3) + ", fixed " + isOdd(-3));        System.out.println("3 factorial(15): buggy " + factorialBuggy(15) + ", fixed " + factorial(15));        int x = 1, y = 2;        swapBuggy(x, y);        int[] pair = {1, 2};        swap(pair, 0, 1);        System.out.println("4 swap(1, 2):    buggy " + x + " " + y + ", fixed " + pair[0] + " " + pair[1]);        String result;        try {            result = reverseBuggy("UPI");        } catch (StringIndexOutOfBoundsException e) {            result = "StringIndexOutOfBoundsException";        }        System.out.println("5 reverse(UPI):  buggy " + result + ", fixed " + reverse("UPI"));    }}
Output
1 digits(0):     buggy 0, fixed 1
2 isOdd(-3):     buggy false, fixed true
3 factorial(15): buggy 2004310016, fixed 1307674368000
4 swap(1, 2):    buggy 1 2, fixed 2 1
5 reverse(UPI):  buggy StringIndexOutOfBoundsException, fixed IPU

What this code does

  • Bugs 1 and 2 hide in edge values (0 and negatives); bug 3 is silent overflow that still prints a plausible number.
  • Bug 4 is a concept bug: Java passes a copy of each int, so swapping inside the method cannot change the caller's variables. Bug 5 is an off-by-one at the start of a backward loop.

Trace the code

Why digits(0) is 0

public class DigitSteps {
public static void main(String[] args) {
int n = 0;
int count = 0;
while (n > 0) {
n = n / 10;
count++;
}
System.out.println(count);
}
}

Variables

n
0

Output

(nothing printed yet)

Line 3The number we want to count is 0.

Step 1 of 4

Next step

Check your understanding

12 quick questions