Dry run on paper
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A dry run means acting as the Java Virtual Machine on paper: you pick a tiny input and follow every line of your logic step by step. Writing variable values in a small table catches bugs in thirty seconds that would otherwise take twenty minutes to hunt down.
Tracing variables in a table
A dry run is tracing a program by hand, line by line, writing down how every variable changes, to check that it does what you expect.
Trying to track three or four changing variables in your head usually fails by the third loop iteration. Instead, draw a trace table on paper—or type a quick comment table right above your method.
Example 1 · Building a trace table for a loop in comments
public class TraceTableDemo { // Problem: Return the longest streak of strictly increasing adjacent numbers. // Input: [3, 5, 8, 2, 6] // // Trace table: // Step | i | nums[i-1] | nums[i] | streak | maxStreak // -------+---+-----------+---------+--------+---------- // init | - | - | - | 1 | 1 // i = 1 | 1 | 3 | 5 | 2 | 2 // i = 2 | 2 | 5 | 8 | 3 | 3 // i = 3 | 3 | 8 | 2 | 1 | 3 (reset to 1!) // i = 4 | 4 | 2 | 6 | 2 | 3 // exit | 5 (5 < 5 is false) -> return 3 public static int longestIncreasingStreak(int[] nums) { if (nums.length == 0) { return 0; } int streak = 1; int maxStreak = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { streak++; if (streak > maxStreak) { maxStreak = streak; } } else { streak = 1; } } return maxStreak; }
public static void main(String[] args) { int[] data = {3, 5, 8, 2, 6}; System.out.println("Longest streak: " + longestIncreasingStreak(data)); }}Longest streak: 3
What this code does
- Row
i = 3in the trace table makes a crucial detail obvious: when2breaks the streak after8,streakmust reset to1(because2itself is a streak of length 1), not0. - Checking
nums.length == 0before initializingstreak = 1handles the empty-array case cleanly.
Give each variable its own column (i, nums[i], sum, max) and add a new row every time an iteration finishes. That way, your eyes only have to check the previous row, leaving your brain free to spot mistakes.
Keep these habits: Row 0 ('init'): Write the starting value of every variable before the loop begins. One column per expression: Include array lookups like nums[i] and conditions like nums[i] > max. Never skip 'obvious' steps: Most bugs hide in the step you assumed was too simple to write down.
// comment block in the editor.Tracing loops step by step
To trace a loop accurately, follow the exact order Java executes it: check the condition first, run the body top to bottom, update the loop counter, and check the condition again.
int[] nums = {4, 7, 2};int sum = 0;for (int i = 0; i < nums.length; i++) { sum += nums[i];}// i | i < 3 ? | sum// - | - | 0 <- init row// 0 | true | 4// 1 | true | 11// 2 | true | 13// 3 | false | 13 <- exit row: the loop stopsAlways write the exit row—the moment the loop condition finally becomes false. Off-by-one bugs almost always show up on the first iteration (i = 0) or the exit check (i == nums.length).
- Write the
initrow before the loop starts. - Check the loop condition (
i < nums.length). Iffalse, stop. - Execute each line in the loop body in order, updating columns left to right.
- Apply the loop update (
i++) and repeat from step 2.
Trace table for the sum loop
Step 1 of 5
| Row | i | i < 3 | sum |
|---|---|---|---|
| start | - | - | 0 |
| pass 1 | |||
| pass 2 | |||
| pass 3 | |||
| exit |
Catching bugs before you run anything
Three bugs cause the majority of wrong answers in beginner and intermediate code, and a 4-row dry run exposes all three before you press Run.
Example 2 · Catching an order-of-update bug with a 3-row dry run
import java.util.Arrays;
public class OrderOfUpdateBugDemo { // Goal: Replace each element with the sum of itself and the previous element // in the ORIGINAL array (index 0 stays unchanged). // Example: [10, 20, 30] -> [10, 30, 50]
// Buggy: overwrites nums[i] going left to right, so i = 2 uses the NEW nums[1]! // Trace on [10, 20, 30]: // i = 1: nums[1] = 20 + 10 = 30 -> array is [10, 30, 30] // i = 2: nums[2] = 30 + 30 = 60 -> array is [10, 30, 60] (WRONG, wanted 50!) public static int[] buggyPairwiseSums(int[] nums) { int[] copy = Arrays.copyOf(nums, nums.length); for (int i = 1; i < copy.length; i++) { copy[i] = copy[i] + copy[i - 1]; } return copy; }
// Fixed: loop right to left (from n - 1 down to 1) so copy[i - 1] is still original! public static int[] fixedPairwiseSums(int[] nums) { int[] copy = Arrays.copyOf(nums, nums.length); for (int i = copy.length - 1; i >= 1; i--) { copy[i] = copy[i] + copy[i - 1]; } return copy; }
public static void main(String[] args) { int[] input = {10, 20, 30}; System.out.println("Buggy : " + Arrays.toString(buggyPairwiseSums(input))); System.out.println("Fixed : " + Arrays.toString(fixedPairwiseSums(input))); }}Buggy : [10, 30, 60] Fixed : [10, 30, 50]
What this code does
- On a 3-element array
[10, 20, 30], a two-row trace immediately shows that updatingcopy[1]first destroys the original20needed bycopy[2]. - Looping backwards from
copy.length - 1down to1readscopy[i - 1]beforecopy[i - 1]is ever modified.
Example 3 · Catching a missing-reset bug in nested loops
public class MissingResetBugDemo { // Goal: Return the maximum number of 1s in any row of a 2D grid.
// Buggy: rowCount is declared OUTSIDE the outer loop, so it never resets! public static int buggyMaxRowOnes(int[][] grid) { int maxOnes = 0; int rowCount = 0; // Bug: accumulates across all rows! for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] == 1) { rowCount++; } } maxOnes = Math.max(maxOnes, rowCount); } return maxOnes; }
// Fixed: declare rowCount = 0 inside the outer loop so each row starts fresh public static int fixedMaxRowOnes(int[][] grid) { int maxOnes = 0; for (int r = 0; r < grid.length; r++) { int rowCount = 0; for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] == 1) { rowCount++; } } maxOnes = Math.max(maxOnes, rowCount); } return maxOnes; }
public static void main(String[] args) { int[][] seats = { {1, 0, 1}, {0, 1, 1} }; System.out.println("Buggy max ones: " + buggyMaxRowOnes(seats)); System.out.println("Fixed max ones: " + fixedMaxRowOnes(seats)); }}Buggy max ones: 4 Fixed max ones: 2
What this code does
- Tracing the start of row
r = 1inbuggyMaxRowOnesshowsrowCountis still2from row0instead of0. - Declaring
int rowCount = 0;inside the outer loop guarantees a clean reset on every row.
An off-by-one error happens when a loop starts or stops one index too early or too late (such as < nums.length - 1 when you needed < nums.length). A missing reset happens when a variable declared outside a loop keeps its old value on the next group. An order-of-update bug happens when you overwrite a variable on line A before line B finishes using its old value.
Check these three things: Off-by-one: Check whether the first index (0) and the last index (n - 1) both appear in your trace table. Missing reset: Check what value an inner-loop counter or flag starts with on the second outer iteration. Order of update: Check whether updating prev before using prev destroys the value you needed.
Trace the code
Trace the missing reset
Step through the program and watch total.
Variables
- total
- 0
Output
(nothing printed yet)Line 4total starts at 0. marks holds two students: {4, 6} and {5, 3}.
Dry running someone else's code
In placement MCQs, technical interviews, and workplace code reviews, you often have to read code you did not write. The biggest trap is guessing what the code does from the method name or variable names.
Example 4 · Dry running unfamiliar code line by line
public class DryRunUnfamiliarCodeDemo { // Unfamiliar method from a code review—trace it on [4, 1, 3, 2]: // init : left = 0, right = 3, score = 0 // step 1 (0 < 3): nums[0] (4) > nums[3] (2) -> score += 4 - 2 = 2; left = 1 // step 2 (1 < 3): nums[1] (1) <= nums[3] (2) -> score += 2 - 1 = 3; right = 2 // step 3 (1 < 2): nums[1] (1) <= nums[2] (3) -> score += 3 - 1 = 5; right = 1 // exit (1 < 1 is false) -> return 5 public static int mysteryScore(int[] nums) { int left = 0; int right = nums.length - 1; int score = 0; while (left < right) { if (nums[left] > nums[right]) { score += nums[left] - nums[right]; left++; } else { score += nums[right] - nums[left]; right--; } } return score; }
public static void main(String[] args) { System.out.println("Mystery score: " + mysteryScore(new int[]{4, 1, 3, 2})); }}Mystery score: 5
What this code does
- By recording
left,right, andscoreat eachwhilecheck, you can predict the exact output5without guessing. - Notice how the exit condition
left < rightstops as soon asleftandrightmeet at index1.
Instead, ignore what the method claims to do and trace a 3-element array through the exact statements written on the page. If a method is named findMax but the if statement says nums[i] < result, your trace table will follow < and find the truth immediately.
Remember: Treat the code like a machine: execute what is written, not what the author intended. Watch integer division: in Java, 5 / 2 is 2, not 2.5. Watch short-circuit operators: in a && b, if a is false, b never runs.
Next step
Check your understanding
10 quick questions