next up previous
Next: Execution of the program Up: Unit 10 Previous: Techniques for detecting errors

Debugging by inserting output statements

This debugging technique is based on inserting in suitable positions of the source code statements that print the content of variables that could contain wrong values causing an error.

Example:

int a, b, x;
a = 5;
b = Integer.parseInt(kb.readLine()); // reading of b
...         // statements that do not change b
x = a/b;

To debug this program statement we can verify, by printing the value of b on the screen, that the error occurs when the variable b has value 0.

int a, b, x;
a = 5;
b = Integer.parseInt(kb.readLine()); // reading of b
...         // statements that do not change b
System.out.println("b = " + b);
x = a/b;

Once the causes for the error have been identified and corrected, the print statements can be removed before closing the debugging session.

Note: If it is necessary to explore the content of objects, rather than of simple variables of primitive data types, we can make use of the toString() method, which provides information on the content of the object. We could also redefine toString() so as to simplify the reading of the state of the object during debugging.


next up previous
Next: Execution of the program Up: Unit 10 Previous: Techniques for detecting errors