DEV Community

Manikanta Yarramsetti
Manikanta Yarramsetti

Posted on

Debugging Java in IntelliJ

Step 1 — Set a breakpoint

Click on the line number in your code. A red dot appears. That is your
breakpoint. The code will stop right there when you run it.

setting a breakpoint in IntelliJ

Step 2 — Run in debug mode

Don't click the green play button. Click the bug icon next to it instead.
Or right click near your main method and select Debug.

running debug mode in IntelliJ

Now when your code hits the breakpoint it stops and you can see everything.

Step 3 — Look at your variables

This is the best part. At the bottom you get a panel showing all your
variables and their current values at that exact moment.

variables panel showing execution point

No more guessing. You just see it.

Moving through the code

Once it stops you have a few buttons to move through the code:

F8 — Step Over
Goes to the next line. Does not go inside any method. I use this one most.

step over in IntelliJ debugger

F7 — Step Into
Goes inside the method on that line. Use this when you want to see what
is happening inside a method.

step into in IntelliJ debugger

Shift F8 — Step Out
You went inside a method and now want to come back out. This does that.

F9 — Resume
Continue running until the next breakpoint.

Conditional breakpoints — big time saver

Got a loop running 500 times and the bug only happens at index 200?
You don't want to press F9 two hundred times.

Right click the red dot and you will see a condition field. Type something
like i == 200 and it only stops when that is true.

conditional breakpoint in IntelliJ

Evaluate Expression

Press Alt + F8 while debugging. A small window opens where you can
type any Java expression and run it right there on the spot.

Want to check what a method returns with a specific value? Just type
it and see. No need to change code and restart.

evaluate expression in IntelliJ debugger

Quick example

Say something is wrong with this:

public int getTotal(List<Integer> numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}
Enter fullscreen mode Exit fullscreen mode

Put a breakpoint inside the loop. Run debug mode. Press F8 each step
and watch total and num change in the variables panel. You will
immediately see which iteration is wrong.

No println needed.

That is it

Start with just a breakpoint and F8. Get comfortable. Then slowly
try the rest.

Once it clicks you will never go back to println debugging. It is
just so much faster and clearer.


Top comments (0)