Learn how to use the pause-step Java Debugger on CodeHS
Debuggers are very useful tools for analyzing the execution of your program. Debuggers allow you to pause your program while it is running, and slowly step through the code line by line to see the flow of execution. You can also print out the values of each variable at each step of your program.
To use the CodeHS Debugger, you'll want to first go to your Account Settings and switch your preferred IDE from Original to Abacus.
The CodeHS IDE allows you to pause and step through your Java programs by entering "Debug Mode" in your editor settings:
Let's try out the debugger on a real program! Press "Run" to start the debugger, and "Step" to start stepping through the code
The debugger provides a few options for stepping through the code:
Try using Step and Next in this program!
While debugging your program, you can use the print and dump commands to print out the values of the variables in your code:
Step to line 10 of this program, then:
Now step to line 16 of this program, then:
What if you want to pause your program on a specific line of code? This is where breakpoints come in handy.
While using the debugger, you can click on any line number to set a breakpoint at that line. When the debugger Runs or Continues, it will pause once it hits that line of code.
Try setting some breakpoints in the following program!
Click on a line number to set a breakpoint at that line.
Press Run to start the program and pause at the first breakpoint you set.
Press Continue to continue to the next breakpoint.
Breakpoints must be put in place before you press Run.
If you modify your breakpoints while your program is running, you'll need to re-run your program in order to pause at your new breakpoints.
You may have noticed that providing input to the program while debugging can be tricky. The debugger tries to interpret your input as debugger commands, but numbers like "10" or "20" are not valid debugger commands.
The fix is to simulate input by creating your Scanner from a String of input, rather than from System.in
// Simulates inputting 10 and then 20 while the program is running
Scanner = new Scanner("10\n20\n");
Curious to Learn More?
CodeHS is using the industry standard built-in Java debugger, JDB, to pause and step through your Java programs.
In this tutorial, you learned about using the following JDB commands:
These are the main commands you'll be using to debug Java programs, but you can check out all the JDB commands at your disposal by reading the JDB Documentation