Concepts / Tracing Program Execution

Tracing Program Execution

The ListLetters program reads a line of text entered by the user and stores it in a String variable named str.

  • Programming

Why Trace a Program Before Running It

When a program produces a surprising result, the fastest way to find the cause is rarely to guess. A more reliable method is to trace execution: follow the program one step at a time, and at each step ask what each named variable holds. This article uses a Java program called ListLetters as its example. Its declarations and its input step are small enough to follow completely, which makes it a good place to practice this habit.

Tracing only works if you know what each variable is supposed to hold. Before you can say that a value is wrong, you need a clear statement of what the value should be. The ListLetters source provides that statement for each variable, in a comment next to its declaration.

What ListLetters Is Meant to Do

According to its own comments, ListLetters reads a line of text entered by the user, prints a list of the letters that occur in that text, and reports how many different letters were found. The program appears under the heading Nested for Loops Exercise, so its work is not only to store the input but to walk through the text character by character and then report what it found.

Key Takeaways

  • A trace follows a program one statement at a time and checks each variable against its stated purpose.
  • ListLetters declares str as a String, count as an int, and letter as a char, and each type matches the job the variable does.
  • str receives the whole line the user types, letter handles one character at a time, and count reports how many different letters were found.
  • If str holds the wrong text, look at input reading; if str is correct but the final count is wrong, look at the work done after the text is read.