Practice: debugging
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
ShopLite's tests pass, then a customer reports a wrong total, a 500 error and a slow checkout. These drills put the whole module together: traces, breakpoints, small buggy programs and the production-issue answer.
Reading a stack trace to the failing line
Example 1 crashes on a mistyped SKU in the second cart. Read the trace in the fixed order: type and message, top frame, your first frame, then the caller that passed the bad value.
Example 1 · A trace that points one frame too high
import java.util.Map;
public class CartCheckoutCrash { static final Map<String, Integer> PRICES = Map.of("BK-CLEAN", 499, "BK-ATOMIC", 399, "ACC-AD141", 1299);
static int priceOf(String sku) { return PRICES.get(sku); }
static int lineTotal(String sku, int quantity) { return priceOf(sku) * quantity; }
static int checkout(String[] skus, int[] quantities) { int total = 0; for (int i = 0; i < skus.length; i++) { total += lineTotal(skus[i], quantities[i]); } return total; }
public static void main(String[] args) { System.out.println("Cart 1: Rs " + checkout(new String[] {"BK-CLEAN", "ACC-AD141"}, new int[] {1, 2})); System.out.println("Cart 2: Rs " + checkout(new String[] {"BK-ATOMIC", "BK-CLEEN"}, new int[] {1, 1})); }}Cart 1: Rs 3097 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null at CartCheckoutCrash.priceOf(CartCheckoutCrash.java:7) at CartCheckoutCrash.lineTotal(CartCheckoutCrash.java:11) at CartCheckoutCrash.checkout(CartCheckoutCrash.java:17) at CartCheckoutCrash.main(CartCheckoutCrash.java:24)
What this code does
- The message names the exact problem: the return value of
Map.getwas null whenintValue()was called for theintreturn type. - Reading down the frames:
priceOf7 failed,lineTotal11 andcheckout17 passed the SKU along, andmain24 suppliedBK-CLEEN.
The message says Map.get returned null and Java then called intValue() on it: an unknown SKU was looked up and auto-unboxed into an int. The top frame priceOf, line 7, is where it failed, but the bad value came from main, line 24, which sent BK-CLEEN, a typo for BK-CLEAN.
Decide where the fix belongs: here, priceOf should reject an unknown SKU with a clear message instead of a NullPointerException (Practice 1). Review: Reading stack traces (opens in a new tab).
Choosing the right breakpoint for a scenario
Each kind of breakpoint answers one kind of question. Match the question to the tool before you start clicking:
Scenario Breakpoint to useWrong value only on the 500th loop pass conditional (i == 499) or pass/hit count 500An exception is caught and hidden exception breakpoint, Caught ticked"Who changes this field?" field watchpointValues over a long loop, without pausing logging breakpoint / logpointA request inside a running Spring Boot app line breakpoint + curl; suspend Thread onlyA JVM started outside the IDE -agentlib:jdwp ... address=localhost:5005, then attachReview: Conditional breakpoints (opens in a new tab) and Debugging a running Spring Boot app (opens in a new tab).
Predict the output
Pick the breakpoint
Match each situation to the breakpoint that answers its question.
Round 1 of 3
A fee is wrong only for roll number 4521 among 3000 students. Which breakpoint do you use?
Finding bugs in small programs
Example 2 shows == working for one input and failing for another. Small programs fail in the same few ways, so check this list first when a result is wrong.
Example 2 · == works for one input and fails for another
public class CouponCompareBug { static int discountPercent(String typed) { String code = typed.strip().substring(0, 6).toUpperCase(); if (code == "FEST20") { return 20; } return 0; }
public static void main(String[] args) { System.out.println("FEST20 -> " + discountPercent("FEST20") + "%"); System.out.println(" fest20 now -> " + discountPercent(" fest20 now") + "%"); }}FEST20 -> 20% fest20 now -> 0%
What this code does
- For
"FEST20",strip,substring(0, 6)andtoUpperCasehave nothing to change and return the same String object, the literal, so==happens to be true. - For
" fest20 now"each call builds a new String. Evaluatecodewhile paused and it shows"FEST20", yetcode == "FEST20"is false:==compares object identity, not text.
Example 3 · The fix: compare text with equals
public class CouponCompareFixed { static int discountPercent(String typed) { String code = typed.strip().substring(0, 6).toUpperCase(); if (code.equals("FEST20")) { return 20; } return 0; }
public static void main(String[] args) { System.out.println("FEST20 -> " + discountPercent("FEST20") + "%"); System.out.println(" fest20 now -> " + discountPercent(" fest20 now") + "%"); }}FEST20 -> 20% fest20 now -> 20%
What this code does
equalscompares the characters, so both inputs get 20%.- This bug survived the developer's own test because they typed exactly
FEST20. Testing with the input real users send (spaces, lower case) is what exposed it.
Check these first:
- Boundaries:
>where the rule says "or more",<=on the last index, a loop that starts one too late. - Integer arithmetic:
present / total * 100is 0 for 68 of 80; multiply first, or usedouble. ==on objects: Strings andIntegervalues outside -128 to 127 must be compared withequals(Examples 2 and 3).- Hidden
nulland shared state:Map.getfor a missing key, a list changed while a for-each loop walks it, aHashSetof a class withoutequalsandhashCode.
Find the bug
Spot the classic bug
Each program gives a wrong result. Find the line that causes it.
The rule says you can vote from the age of 18. Which line is wrong?
Round 1 of 4Interview drill: how do you debug a production issue
"How do you debug a production issue?" checks whether you have a calm, safe routine. A good answer has these steps, in this order:
- Limit the damage: how many users are affected? Roll back the release or switch the feature off if needed.
- Collect facts: the error log with time, request and stack trace, the version deployed, recent changes, monitoring graphs.
- Reproduce it outside production, on your machine or a test server, with the same input, data and configuration.
- Narrow it down and test one hypothesis at a time with the debugger and extra logs there, never by pausing production.
- Fix it with a regression test first, deploy, and watch the logs and metrics to confirm.
- Write a short note: cause, fix, and what will catch it earlier next time (a test, an alert, a validation).
Finish up
Mark complete & continue
Next: Mini project: hunt three bugs in ShopLite