Execution Flow and Dry Running
Knowing Java syntax is only the beginning. A strong programmer must also understand: What does the computer do first, second, third, and so on?
One of the best ways to develop this skill is called dry running.
What Is a Dry Run?
A dry run means manually pretending to be the computer. You take a program and trace it step by step. For every important line, you ask:
- What line is executing?
- What are the current variable values?
- Is a condition true or false?
- What gets printed?
This is one of the most useful skills for debugging and understanding algorithms.
Example Program
Consider this program:
public class DryRunExample { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 5; i++) { if (i % 2 == 0) { sum = sum + i; System.out.println("Added: " + i); } } System.out.println("Sum: " + sum); }}The output is:
Added: 2
Added: 4
Sum: 6
But how did Java arrive at this output? Let's step through it interactively!
Interactive Step Debugger & Live Watch 🕹️
Step forward line by line or click Auto-Step below to watch variables sum and i, condition evaluations, and console outputs update in real time:
Initialize accumulator variable 'sum = 0' in the stack frame.
Complete Dry Run Reference Table
The following table tracks the execution steps line-by-line, showing what the computer evaluates at each transition:
| Step | Line | Variable States | Output | Explanation |
|---|---|---|---|---|
| 1 | 3 | sum = 0 | — | Initialize sum |
| 2 | 5 | sum = 0, i = 1 | — | Loop starts |
| 3 | 6 | sum = 0, i = 1 | — | 1 % 2 == 0 is false |
| 4 | 5 | sum = 0, i = 2 | — | Loop increments i |
| 5 | 6 | sum = 0, i = 2 | — | 2 % 2 == 0 is true |
| 6 | 7 | sum = 2, i = 2 | — | sum = 0 + 2 |
| 7 | 8 | sum = 2, i = 2 | Added: 2 | Print statement |
| 8 | 5 | sum = 2, i = 3 | — | Loop increments i |
| 9 | 6 | sum = 2, i = 3 | — | 3 % 2 == 0 is false |
| 10 | 5 | sum = 2, i = 4 | — | Loop increments i |
| 11 | 6 | sum = 2, i = 4 | — | 4 % 2 == 0 is true |
| 12 | 7 | sum = 6, i = 4 | — | sum = 2 + 4 |
| 13 | 8 | sum = 6, i = 4 | Added: 4 | Print statement |
| 14 | 5 | sum = 6, i = 5 | — | Loop increments i |
| 15 | 6 | sum = 6, i = 5 | — | 5 % 2 == 0 is false |
| 16 | 5 | sum = 6, i = 6 | — | Loop increments i |
| 17 | 5 | sum = 6, i = 6 | — | 6 <= 5 is false; loop ends |
| 18 | 11 | sum = 6 | Sum: 6 | Final print |
A Golden Rule for Dry Running
Whenever you dry run a program, never try to keep everything only in your head. Write down the important variables on a piece of paper and update them whenever the program changes them.
Don't just read code. Learn to mentally execute it! That skill will become one of your strongest tools as you move from Java basics into Data Structures and Algorithms.