Skip to content
javahacks.dev
Debugging

How to Debug Java in IntelliJ IDEA Like a Pro Step by Step

Set breakpoints, step through code, evaluate expressions, watch variables and use exception breakpoints in IntelliJ IDEA to find bugs faster.

7 min read
Summarize in AI
Flat illustration of a stack trace of frames with a bug beside it, with the OpenJDK, IntelliJ IDEA, Sentry and Spring Boot logos.

A debugger shows what the program is doing, where a print statement shows only what you guessed to print. IntelliJ IDEA's debugger covers most of what you need, and a handful of features make the difference between slow and fast. This post walks through them. The shortcuts below are the default keymap on Windows and Linux; on macOS the Option key replaces Alt and Cmd replaces Ctrl. For Spring-specific techniques see debugging Spring Boot, and for reading errors first, how to read a stack trace.

Start a session

Click in the left gutter next to a line number: a red dot is a breakpoint. Then run the program with the bug icon (Debug) or Shift+F9. Execution stops before the marked line. The Debug tool window shows two panes: Frames (the call stack) and Variables (values in the current frame). Click a frame to see its variables. A test class or a single test method can be debugged the same way from its gutter icon.

Step through code

ActionKeyEffect
Step OverF8Run the current line, stop at the next one in this method
Step IntoF7Enter the method called on this line
Step OutShift+F8Run until the current method returns
ResumeF9Continue to the next breakpoint
Run to CursorAlt+F9Continue to the line under the caret
Smart Step IntoShift+F7Choose which call on a line to enter

Smart Step Into is useful for lines like a(b(c())). Step Into skips library code by default; the Stepping settings choose which classes count as library code.

Look at values

The Variables pane shows objects; expand them to see fields. Hover over a variable in the editor to see its value, and IntelliJ draws values next to the code (inline debugging). Right-click a variable and choose "Add to Watches" to keep an expression visible as you step. For large collections, the pane shows the first elements; use a filter or evaluate an expression like orders.stream().filter(o -> o.total() > 100).toList() to look at a subset.

Evaluate Expression

Press Alt+F8 to open a field that runs any Java expression in the current frame:

java
customer.getOrders().size()
String.join(",", names)

You can call methods, create objects and even assign variables to test a fix without stopping and recompiling. Beware of expressions with side effects, such as calling a method that writes to the database.

Change state while paused

In the Variables pane, press F2 on a value to set it, for example to force a branch. Combined with Drop Frame (Run, Drop Frame, or the toolbar button), you can rewind the current method to its start and run it again with a changed value. Drop Frame cannot undo side effects such as writes or sent messages.

Exception breakpoints

Open the Breakpoints dialog (Ctrl+Shift+F8), add a Java Exception Breakpoint and choose a class such as NullPointerException. The debugger now stops exactly where the exception is thrown, with the full state, instead of where it is eventually caught or logged. This is the quickest way to see why a stack trace shows only a wrapper. Choose "Caught" and "Uncaught" as needed. For a library exception you do not control, this finds the first throw inside it.

Breakpoints with conditions and actions

Right-click a breakpoint to add a condition (stop only when order.id() == 42), a hit count, or a log message instead of stopping. These are covered in conditional breakpoints and logpoints. A breakpoint in a loop with a condition replaces a manual F9 on every iteration.

Debugging threads and deadlocks

The Threads tab lists all threads; switch to see what each is doing. When a program hangs, press the Pause button, then read the stack of the stuck thread. For a deadlock, the thread dump (Run, Get Thread Dump) shows threads blocked on locks, interpreted as in fixing deadlocks.

Hot swap

After editing a method body in a debug session, IntelliJ offers to reload changed classes without restarting. It works for changes inside method bodies, and not for adding fields or methods, which need a restart (unless the JVM supports class redefinition, as with some runtimes).

Habits that pay off

  • Reproduce with a test, and debug the test; it restarts in seconds.
  • Read the stack trace before you set a breakpoint; it tells you where to put it.
  • Remove stale breakpoints; they slow runs and surprise you later.
  • Use the debugger for state you do not understand and logs for events over time.

Try it on a program with a bug

Features are easier to learn on code that is wrong in a way you can predict. This class totals prices by category and has a deliberate mistake: it reads a map entry that does not exist for some products, so the total is silently too low:

java
import java.util.*;

public class BasketTotals {

    record Item(String name, String category, long cents) {}

    static final Map<String, Double> TAX = Map.of("food", 0.07, "books", 0.0);

    public static void main(String[] args) {
        List<Item> basket = List.of(
            new Item("coffee", "food", 1_200),
            new Item("novel", "books", 1_800),
            new Item("lamp", "home", 4_500));

        long total = 0;
        for (Item item : basket) {
            double rate = TAX.getOrDefault(item.category(), 0.0);
            total += Math.round(item.cents() * (1 + rate));
        }
        System.out.println("total cents: " + total);
    }
}

Set a breakpoint on the total += line and run the debugger. Step over once and watch total change in the Variables pane. When the loop reaches the lamp, open Evaluate Expression and type TAX.containsKey(item.category()). The answer is false, so the lamp is taxed at zero without anyone noticing, which is the question the inline values did not answer by themselves. Add a conditional breakpoint with !TAX.containsKey(item.category()) and the debugger now stops only on the products that are missing from the table, and the same condition would stop on the one bad product in a basket of ten thousand. Use Drop Frame to run the iteration again after you change rate in the Variables pane, and compare the totals.

Debug a running service

Often the program is already running, in a container or on a test server. Start the JVM with the debug agent, bound to a local address, and connect from the IDE through an SSH tunnel:

Shell
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005 -jar app.jar
ssh -L 5005:127.0.0.1:5005 test-server

In IntelliJ, create a Remote JVM Debug run configuration with host localhost and port 5005, then press Debug. Breakpoints work as in a local session, as long as the source on your machine matches the version running on the server. When they show as unverified (a grey dot with a slash), the class there differs from yours, or the code was compiled without debug information. Never leave the agent on a production process, because the port gives full control of the JVM to anyone who can reach it.

Threads, streams and the habits that save time

Two more views are worth a few minutes. The Threads tab of the Debug window lists every thread with its state, and switching between them shows what each one is doing at the moment you stopped, which finds a deadlock or a thread stuck in a lock faster than a dump. For a pipeline of stream operations, the Trace Current Stream Chain button shows the elements before and after each stage, so you see which filter dropped the item you expected.

Keep your breakpoints few and named. Put a log message on a breakpoint instead of stopping when you only need to see a value pass, and mute all breakpoints from the toolbar when you want the program to run normally without removing them. When a session is over, delete the ones you will not need, because a conditional breakpoint left on a hot line slows every later run. The habit that pays most is to form a guess before you stop the program: write down what you expect the value to be at the breakpoint. A surprise is the signal, and a debugger session without a prediction is just scrolling.

Where this does not apply

For problems that appear only under concurrency or in production, a debugger changes the timing or is not available; use logs and thread dumps (debugging with only logs). The IntelliJ IDEA debugging documentation and the Java Debug Wire Protocol reference describe the tool and the protocol.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.