Java:
Using a debugger

How to:

Let’s say you’ve got a simple Java program that’s acting up, and you can’t figure out why. Here’s how you’d fire up a debugger using Eclipse, one of the popular IDEs for Java development:

First, make sure you’ve set a breakpoint. Then, right-click on the file, select ‘Debug As’, and click on ‘Java Application’.

public class DebugExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 0;
        // Set a breakpoint here
        int result = divide(a, b);
        System.out.println("The result is: " + result);
    }

    private static int divide(int numerator, int denominator) {
        // Another good spot for a breakpoint
        return numerator / denominator;
    }
}

Doing this, your program will pause at the breakpoint, and you can inspect variables, step through code line by line, and watch how your program behaves.

Sample Output (in a debugger console):

Breakpoint hit at line: int result = divide(a, b);

Deep Dive

The concept of debugging has been around since the early days of programming. Legend has it that the term “bug” actually came from a real-life mothy bug found inside a computer by Grace Hopper, a pioneer in the field. Fast forward to today, and we’ve got sophisticated IDEs like IntelliJ IDEA, Eclipse, and NetBeans that pack powerful debuggers.

Alternatives to IDE debuggers include logging, print statements (poor-man’s debugger), assertions, and standalone debugging tools like jdb (Java Debugger) which is part of the Java Development Kit (JDK).

A debugger works by allowing the programmer to pause execution (breakpoints), step through code, inspect variable values, modify those values on the fly, and even run code block by block. The use of a debugger is often considered an invaluable technique for developing complex applications where tracking down the exact line of code causing a problem can be likened to finding a needle in a haystack.

See Also