Code Tracing and Debugging
Trace variable state, method calls, loops, conditionals, output, and common logic errors in AP-style code segments.
A lesson of AP Computer Science A, in Control Flow and Methods, about 10 minutes.
By the end of this lesson, you will be able to trace code execution manually to determine output, identify common programming errors, and apply debugging strategies.
Code Tracing
Code tracing is manually executing code step-by-step to determine what it does without running it. This is a critical skill for:
- AP exam multiple-choice and FRQ
- Understanding code you didn't write
- Debugging problems
The trace table method: for each step of execution, write down the current value of every variable.
Trace Example
int x = 5;
int y = 2;
int z = 0;
while (x > y) {
z = z + x;
x--;
}
System.out.println(z);
| Step | x | y | z | Condition (x > y) |
|---|---|---|---|---|
| Start | 5 | 2 | 0 | — |
| Iteration 1 | 4 | 2 | 5 | 5 > 2 → true |
| Iteration 2 | 3 | 2 | 9 | 4 > 2 → true |
| Iteration 3 | 2 | 2 | 12 | 3 > 2 → true |
| Check | 2 | 2 | 12 | 2 > 2 → false → EXIT |
Output: 12
Predict It: Trace the Loop
Tracing is the whole skill this lesson is about, so here it is as a question rather than as a worked example you read.
Walk the lines one at a time and keep a note of every variable as it changes.
Predict It: The Off-by-One
The same loop with one character changed. Trace it again rather than assuming.
Common Programming Errors
Syntax errors: invalid Java code that won't compile.
- Missing semicolons
- Mismatched braces or parentheses
- Misspelled variable names
- Wrong data type assignment
Runtime errors (exceptions): the code compiles but crashes during execution.
ArrayIndexOutOfBoundsException: accessing index ≥ length or < 0NullPointerException: calling methods on a null referenceArithmeticException: dividing by zero (integer division)- : invalid type cast