Breakpoints, step over, step into
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's cart shows the wrong total, yet the code looks fine, and reading it again finds nothing. To find the bug, you need to watch the program calculate the total one line at a time.
Starting a program in debug mode
A debugger is a tool built into your IDE that runs your program under its control, so you can pause it at any line, look at every variable and run it one line at a time.
Example 1 is a small cart program: main calls cartTotal, which calls lineTotal once per item. Start it with Debug, not Run. With no breakpoints it prints its two lines, exactly as a normal run would.
Example 1 · The cart program used on this page
public class CartTotalDemo { static int lineTotal(int price, int quantity) { int total = price * quantity; return total; }
static int cartTotal(int[] prices, int[] quantities) { int sum = 0; for (int i = 0; i < prices.length; i++) { sum += lineTotal(prices[i], quantities[i]); } return sum; }
public static void main(String[] args) { int[] prices = {499, 1299, 399}; int[] quantities = {1, 2, 3}; int total = cartTotal(prices, quantities); System.out.println("Items: " + prices.length); System.out.println("Cart total: Rs " + total); }}Items: 3 Cart total: Rs 4294
What this code does
- Started with Debug and no breakpoints, the program runs to the end and prints the same two lines as a normal run: a debugger only pauses where you ask it to.
- Line 10 calls
lineTotalthree times; it is a good line for a breakpoint becausei,sumand the arrays are all visible there.
Debug mode runs your program under the debugger. The code is the same; only the way you start it changes. A normal Run ignores breakpoints, so a program started with Run never pauses.
In IntelliJ IDEA, click the green triangle in the gutter (the strip left of the code) next to main and choose Debug; the Debug tool window opens at the bottom. In VS Code with the Extension Pack for Java, click Debug in the Run | Debug links above main, or press F5. On a laptop where the F keys control brightness and volume, hold fn while you press them.
Line breakpoints and the paused frame
A breakpoint is a marker on a line that tells the debugger to pause the program just before that line runs.
Click in the gutter next to line 10 of Example 1 and a red dot appears. Start with Debug: the program stops on that line. This simplified picture shows the second pass of the loop.
Paused at CartTotalDemo.java, line 10 (this line has NOT run yet)Frames cartTotal, line 10 <- the paused frame main, line 18Variables prices = int[3] [499, 1299, 399] quantities = int[3] [1, 2, 3] sum = 499 i = 1That snapshot of one method call is the paused frame: the method you are in, who called it, and every variable with its current value. Nothing runs until you press a step or resume command, so you can look as long as you like.
To toggle a breakpoint from the keyboard, press Ctrl+F8 in IntelliJ (Cmd+F8 on a Mac) or F9 in VS Code.
Predict the output
What does the paused frame show?
The loop in Example 1 has a breakpoint on line 10. Predict what the debugger shows.
Round 1 of 2
The first time the program pauses on line 10, what is i?
sum still shows 499, the value from before sum += lineTotal(...).Step over, step into, step out, resume and run to cursor
Stepping means running a paused program one small piece at a time. Step over runs the whole line, step into goes inside the method the line calls, and step out finishes the current method.
In Example 2 a student with 90 marks pays the wrong fee. Put a breakpoint on the line that asks for the discount, then use step over and step into to see where the 10 comes from.
Example 2 · Finding a wrong fee by stepping
public class ScholarshipDemo { // Rule from the college notice: 90 marks or more -> 20% off, 75 or more -> 10% off static int discountPercent(int marks) { if (marks > 90) { return 20; } if (marks > 75) { return 10; } return 0; }
static int feeAfterScholarship(int fee, int marks) { int percent = discountPercent(marks); return fee - fee * percent / 100; }
public static void main(String[] args) { String[] names = {"Asha", "Ravi", "Meena"}; int[] marks = {92, 90, 75}; for (int i = 0; i < names.length; i++) { int fee = feeAfterScholarship(60000, marks[i]); System.out.println(names[i] + " (" + marks[i] + "): Rs " + fee); } }}Asha (92): Rs 48000 Ravi (90): Rs 54000 Meena (75): Rs 60000
What this code does
- Ravi has 90 marks and the notice says 90 or more gets 20%, yet he pays Rs 54000. Put a breakpoint on line 14 and step over it:
percentshows 10 formarks90, so the wrong value comes fromdiscountPercent. - On Ravi's pass, step into line 14 instead: the debugger stops on line 4,
marks > 90is false for 90, and stepping reachesreturn 10on line 8. The fix is>=on lines 4 and 7 (Meena's 75 has the same bug). - Step out (Shift+F8 / Shift+F11) from inside
discountPercentreturns you to line 14 withpercentabout to be assigned.
Pick the command that matches what you want to see next:
- Step over (IntelliJ F8, VS Code F10): run the whole current line, including any method it calls, and pause on the next line.
- Step into (IntelliJ F7, VS Code F11): if the line calls one of your methods, go inside it and pause on its first line.
- Step out (IntelliJ Shift+F8, VS Code Shift+F11): finish the current method and pause back in the caller.
- Resume runs to the next breakpoint. Run to cursor runs to the line with your cursor, like a one-time breakpoint.
java.* by default in IntelliJ (Settings → Build, Execution, Deployment → Debugger → Stepping). Use Force Step Into (Alt+Shift+F7 / Option+Shift+F7) when you really want to go inside one.The call stack (frames) panel
The call stack is the list of method calls that are running right now, newest on top. Each entry is a frame: one method call with its own local variables and the line it has reached.
Example 3 prints the frames list from inside lineTotal, using StackWalker. It is the same list that the debugger's frames panel shows when you pause on that line.
Example 3 · The frames list, printed by the program itself
public class FramesDemo { static void printFrames() { System.out.println("Frames, newest first:"); StackWalker.getInstance().forEach(frame -> System.out.println(" " + frame.getMethodName() + ", line " + frame.getLineNumber())); }
static int lineTotal(int price, int quantity) { if (quantity == 2) { printFrames(); // a breakpoint here would show the same list } return price * quantity; }
static int cartTotal(int[] prices, int[] quantities) { int sum = 0; for (int i = 0; i < prices.length; i++) { sum += lineTotal(prices[i], quantities[i]); } return sum; }
public static void main(String[] args) { int total = cartTotal(new int[] {499, 1299, 399}, new int[] {1, 2, 3}); System.out.println("Cart total: Rs " + total); }}Frames, newest first: printFrames, line 4 lineTotal, line 10 cartTotal, line 18 main, line 24 Cart total: Rs 4294
What this code does
StackWalker(Java 9) walks the current thread's call stack. It prints the same list the debugger's frames panel shows if you pause on line 10: newest call on top, each with the line it has reached.cartTotal, line 18andmain, line 24are the lines that made the calls. Those callers are paused in the middle of a line, waiting for the call to return.
IntelliJ shows the list in the Threads & Variables tab of the Debug window; VS Code shows it as CALL STACK.
Click a lower frame to see the caller's variables. Paused in lineTotal, clicking cartTotal shows i = 1 and sum = 499. The program does not move; you only change which frame you look at.
Order of execution
Order the frames panel
You are paused inside lineTotal. Put the frames in the order the panel lists them, newest first.
n.Println debugging vs the debugger
Println debugging means adding temporary System.out.println lines that print values, running the program and reading the output. It needs no tools and works anywhere.
Example 4 adds one DEBUG print to find a wrong average. The print shows sum 247 and count 3, both right, so the bug must be on the return line.
Example 4 · Println debugging finds integer division
public class AverageMarksDemo { static double average(int[] marks) { int sum = 0; for (int m : marks) { sum += m; } System.out.println("DEBUG sum=" + sum + " count=" + marks.length); return sum / marks.length; }
public static void main(String[] args) { int[] marks = {78, 85, 84}; System.out.println("Average: " + average(marks)); }}DEBUG sum=247 count=3 Average: 82.0
What this code does
- The DEBUG line proves the inputs to the division are right (247 and 3), so the bug must be on line 8.
sum / marks.lengthdivides twointvalues, so the result is 82; only then is it widened to thedouble82.0. The fix is(double) sum / marks.length(Practice 3).
Choose by situation:
- Prefer the debugger when you do not know which value is wrong, the bug hides in a chain of calls, or you want to test an idea right away.
- Prefer prints or log lines when the bug appears only on a server, depends on timing between threads, or you need a record of many runs.
- Never commit
DEBUGprints. The Logging for Troubleshooting module shows log lines that are meant to stay.
Fix the error
Fix the wrong value
Both bugs gave a wrong value on the line shown. Pick the line that fixes it.
Round 1 of 2
The average of 78, 85 and 84 prints 82.0, not 82.33. Fix line 2.
Error
Average: 82.0 (expected 82.33)
Next step
Check your understanding
12 quick questions