CSCI 131

Techniques of Programming

Debugging Java Programs

You are now writing programs that are interesting enough to contain subtle bugs. Here are some common ways to debug a Java program:

  1. Stare at it. This is probably what you have been doing up to now.
  2. Add print statements. Perhaps the most common way of debugging programs, this sometimes works surprisingly well. Just add System.out.println() statements, or StdOut.println(), at key points (or generously!) throughout your program. Inside a conditional, you might insert:
      System.out.println("I'm now inside the TRUE part of the conditional");
    Inside your LookupCode function you might put this near the start:
      System.out.println("LookupCode was called with target value " + target);
    and near each return statement put:
      System.out.println("LookupCode is about to return character " + letter);
    The result is that when you run your program, you get a nice printout showing how conditionals were executed, which functions were called, the value of important parameters and variables, what values were returned, etc.
  3. Test it. Run your code with many different inputs to watch how it behaves. With good planning and a little luck, knowing which inputs work and which inputs don't work can help lead you to the bug.
  4. Use a debugger like jdb. Debuggers can be hard to learn and easy to forget, but this method gives you the most information about what is happening inside your program.

jdb Cheat Sheet

jdb is a command-line debugger for java programs. It lets you run your code, but slowly... you can step through your code one line at a time, you can pause the program and examine the values of your program variables, and so on.

Starting the debugger (using one terminal window). In the terminal, change to the directory where your program is stored. Then instead of running java ClassName, run this command:

    jdb ClassName

For example, you might run jdb HelloWorld. This way of starting jdb only really works for programs that do not use standard input.

Starting the debugger (using two terminal windows). If your java program uses standard input, you need to use two terminal windows: one for the program, one for jdb. Open two terminals, and in both change to the directory where your program is stored. In one window, run your class like this:

    java -agentlib:jdwp=tranport=dt_socket,address=8888,server=y,suspend=y ClassName 

Now, in the second window, run this command:

    jdb -attach 8888

Use your second window for jdb, as described below. use the first window for the program. Note: You can change the number 8888 (in both commands) if it complains that address 8888 is busy.

Getting help.

Set a breakpoint.

Start the program.

Resuming after hitting a breakpoint.

Getting information after hitting a breakpoint.