Newer
Older
labs / tiddlywiki / tiddlers / content / labs / lab01 / _labs_lab01_Exercise_ Debugging.md

Sometimes you find yourself in the situation where you are getting an error while your program is running and you can’t figure out what is causing the problem.

One approach to helping you figure out what is causing the problem is to put lots of System.out.println statements in your code to print out the value of variables and show the path that the execution takes through your code.

A better solution is to use a debugger.

  1. Add the following code to your main method (delete everything else in the method):

    for(int i=0; i<10; i++) {
       int x = i * 2;
       System.out.println(x);
    }
  2. Click on the line number to the left of the line of code that starts with int x.

    You should see a little red square appear where you clicked and the line will be highlighted red.

    This is what we call a break point. This will tell the debugger that we want it to stop the program at this point so that we can have a look at the internals of the program.

  3. Right click in the editor and select <

    >.

    This will start the debugger. The program will run until it hits the break point and then pause. You can tell which line of code the debugger has stopped at since it will be highlighted green.

  4. Hold your cursor over the i variable. You should see a tool-tip containing the current value of i.

  5. Notice that there are several new icons on the main toolbar when you are running the debugger. These are for controlling how the debugger will execute your program.

    Find the Step Over icon on the main toolbar. This will advance the execution to the next line.

  6. Keep clicking Step Over and notice how the execution cycles through your loop.

    Hold your cursor over the i and x variables and notice how the value changes.

  7. Open the local variables pane from <

    Debugging">> . This pane will show you all of the variables and their values.

If you have a variable that is an object then you can drill down into the object to examine its contents.

Try to remember to use the debugger — if your program isn’t working the way you intended it to then the debugger will definitely help you figure out why.