Java Debugging Tips: Practical Techniques Beyond the Debugger
Practical Java debugging tips: useful toString methods, logging proxies, stack traces on demand, capturing stderr, uncaught exception handlers, javac -Xlint, -verbose and -Xlog, and JVM tools like jcmd, jconsole, VisualVM, Java Flight Recorder and Mission Control.
kvi5hnuCode Sprout team member11 min readOn this page
Suppose you've written your program and made it robust by catching and handling every exception properly. You run it, and it doesn't work right. Now what? (If that never happens to you, feel free to skip this article.)
The most powerful tool is a good debugger. IntelliJ IDEA, Eclipse, VS Code and NetBeans all include one, with breakpoints, stepping, variable watches and expression evaluation. Learn yours well. But there are many situations where a debugger is awkward or unavailable: a problem that only occurs on a server, a race condition that disappears when you pause, a performance issue, a crash at a customer site. This article collects techniques that work in those cases and complement the debugger.

1. Print or log any value, and give classes a good toString
The simplest technique still works:
System.out.println("x=" + x);
or, better, because it can stay in the code:
logger.log(DEBUG, "x=" + x);
If x is a number, it's converted to a string. If it's an object, its toString method is called. Logging the state of the current object can be revealing too:
logger.log(DEBUG, "this=" + this);
Most library classes override toString with useful information. This is a real help when debugging, so make the same effort in your classes. Records do it automatically. Without toString, all you get is something like Opaque@1b6d3586. IDEs can generate toString for ordinary classes.
2. Give classes a demo main method
You can put a separate main method in any class, containing code that shows how the class is meant to be used:
public class MyClass {
methods and fields
. . .
public static void main(String[] args) {
demo code
}
}
Make a few objects, call methods, and check that each does the right thing. With single-file source launching (java MyClass.java) and jshell, quick experiments like this are easier than ever.
3. Write unit tests
For professional testing, use a unit testing framework. JUnit (at junit.org; JUnit 6, released in September 2025, needs Java 17+ and keeps the "Jupiter" programming model introduced by JUnit 5) is the standard in the Java world. It makes it easy to organize suites of test cases. Run the tests whenever you change a class, and add a new test whenever you find a bug. That bug can then never come back unnoticed. Test-friendly code also tends to be easier to debug: small methods, clear inputs and outputs, few hidden dependencies.
4. Use a logging subclass or proxy
Suppose you suspect a problem with the nextDouble method of Random. You can intercept the calls with an anonymous subclass that logs each call and then does the original work:
var generator = new Random() {
public double nextDouble() {
double result = super.nextDouble();
logger.log(DEBUG, "nextDouble: " + result);
return result;
}
};
Every call to nextDouble now produces a log message. This only works if the class and method aren't final. For interfaces, a dynamic proxy can log every method at once, as shown in the dynamic proxies article.
5. Peek at exceptions on the way through
printStackTrace prints the stack trace of any exception. To observe an exception without changing the program's behavior, catch it, print it, and rethrow it so it still reaches its intended handler:
try {
. . .
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
Thanks to precise rethrow, this doesn't even change the method's throws clause. Remove it once you're done: catching Throwable doesn't belong in finished code.
You don't need an exception to get a stack trace. Insert
Thread.dumpStack();
anywhere, and the current stack is printed to System.err. It's an easy way to answer "who is calling this method?".
6. Capture a stack trace as a string
Stack traces go to System.err by default. To log or display one, capture it:
var out = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(out));
String description = out.toString();
To pick out specific frames programmatically, use StackWalker (see the article on stack traces).
7. Redirect System.err to a file
It's often handy to collect a program's errors in a file. Errors go to System.err, not System.out, so this does not capture them:
java MyProgram > errors.txt
Redirect the error stream instead:
java MyProgram 2> errors.txt
To capture both System.out and System.err in the same file:
java MyProgram 1> errors.txt 2>&1
This works in bash, zsh and the Windows command shell. In PowerShell, *> redirects all streams.
8. Handle uncaught exceptions yourself
Stack traces of uncaught exceptions dumped on System.err aren't ideal. They confuse users who happen to see them, and they're not available for diagnosis when you need them. It's better to log them. Install a handler for uncaught exceptions with the static Thread.setDefaultUncaughtExceptionHandler method:
Thread.setDefaultUncaughtExceptionHandler((t, e) ->
logger.log(ERROR, "Uncaught exception in thread " + t.getName(), e));
The handler runs in the thread that died, just before it terminates. Other threads, including main, carry on. A per-thread handler can be set with thread.setUncaughtExceptionHandler.
9. Watch class loading
Launch the JVM with -verbose:class (or just -verbose) to see every class as it's loaded:
[0.012s][info][class,load] opened: /usr/lib/jvm/jdk-25/lib/modules
[0.034s][info][class,load] java.lang.Object source: shared objects file
[0.035s][info][class,load] java.io.Serializable source: shared objects file
[0.035s][info][class,load] java.lang.Comparable source: shared objects file
[0.035s][info][class,load] java.lang.CharSequence source: shared objects file
[0.035s][info][class,load] java.lang.String source: shared objects file
. . .
This occasionally helps diagnose class path problems, such as a class loaded from an unexpected JAR or two versions of a library. The same output is available through the JVM's unified logging as -Xlog:class+load. Run java -Xlog:help to see the many other things it can log, including garbage collection, safepoints and JIT compilation.
10. Let the compiler find problems: -Xlint
The -Xlint option tells the compiler to report common code problems that are legal but questionable. ("Lint" originally named a tool that found such problems in C programs. Today the word covers any such checker.) For example:
javac -Xlint sourceFiles
reports missing break statements in switch statements:
warning: [fallthrough] possible fall-through into case
The word in square brackets is the warning category. Most categories are useful, so the best approach is to enable all of them and switch off only the ones you don't care about:
javac -Xlint:all,-fallthrough,-serial sourceFiles
javac --help-lint lists all categories. Consider -Werror, which turns warnings into errors, in continuous integration builds. Static analysis tools such as SpotBugs, Error Prone, PMD, SonarQube and IDE inspections go much further than -Xlint.
11. Monitor a running JVM with jconsole and JMX
The JVM supports monitoring and management through JMX, so tools can track memory, threads, class loading and more in a running program. This matters especially for large, long-running applications. The JDK includes a graphical tool, jconsole. Start your program, start jconsole, and pick your program from the list of local Java processes. You'll see:
- live charts of heap usage, thread count, loaded classes and CPU;
- per-thread stack traces and deadlock detection;
- MBeans, including the logging bean, where you can change logger levels at run time.
12. Profile with Java Flight Recorder
Java Flight Recorder (JFR) is built into the OpenJDK virtual machine. It records diagnostic and profiling data, such as CPU hot spots, allocations, garbage collections, lock contention and I/O, with very low overhead, low enough to leave on in production. Start a recording at launch:
java -XX:StartFlightRecording=duration=60s,filename=rec.jfr MyApp
View recordings with JDK Mission Control (JMC) or VisualVM, open-source tools that can also do everything jconsole does. The JDK's jfr command-line tool can print and summarize recordings too (jfr print, jfr summary, and jfr view since Java 21).
13. Use jcmd, the Swiss army knife
The JDK ships several command-line monitoring tools with overlapping features: jcmd, jhsdb, jinfo, jmap, jps, jstat. Start with jcmd, which covers most of their uses. With no arguments, it lists all Java processes on the machine, with their process IDs and main classes:
jcmd
Then send commands to a process, identified by its PID or main class name:
| Command | What it does |
|---|---|
jcmd pid VM.system_properties | List system properties |
jcmd pid VM.flags | Show VM flags |
jcmd pid VM.log output=gc.log what=gc | Configure VM logging at run time |
jcmd pid Thread.print | Print a thread dump: every thread's state and stack. The first step for a hang or deadlock |
jcmd pid Thread.dump_to_file -format=json file | Dump threads to a file (Java 21). Includes virtual threads |
jcmd pid GC.heap_info | Heap usage summary |
jcmd pid GC.heap_dump file.hprof | Write a heap dump for memory-leak analysis |
jcmd pid JFR.start filename=rec.jfr | Start a flight recording |
jcmd pid JFR.stop name=1 | Stop it |
jcmd pid or jcmd pid help | List available commands |
jcmd pid help commandName | Help for one command |
More tips from the field
- Read the whole exception. The message, the first frame in your code, and the deepest
Caused by:usually point straight at the problem. HelpfulNullPointerExceptionmessages even tell you which variable wasnull. - Reproduce first, then shrink. Find reliable steps that trigger the bug, then cut away code and input until the smallest failing case remains. Often the cause is obvious by then.
- Check your assumptions with assertions and run with
-eaduring development. - Use exception breakpoints. Most debuggers can stop when a given exception type is thrown, even if it's caught and swallowed somewhere.
- Use
git bisectto find the exact commit that introduced a regression. - Explain the problem out loud, to a colleague or a rubber duck. Describing what the code should do often reveals what it actually does.
A complete example
The program shows:
toStringoutput from records, compared with a class that has none;- a logging subclass of a seeded
Random; - peeking at an exception and rethrowing it;
- a stack trace captured as a string;
- a default uncaught exception handler catching a crash in a worker thread while
maincontinues.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws InterruptedException {
// Tip 1: good toString methods make print/log debugging painless
var item = new Item("Widget", 3, 9.99);
var order = new Order(1001, new ArrayList<>(List.of(item, new Item("Gadget", 1, 24.5))));
System.out.println("order=" + order);
System.out.println("without toString: " + new Opaque().toString().replaceAll("@\\p{XDigit}+", "@<hash>"));
// Tip 4: a logging "proxy" via an anonymous subclass
var generator = new Random(42) {
@Override
public double nextDouble() {
double result = super.nextDouble();
System.out.printf("nextDouble: %.4f%n", result);
return result;
}
};
double sum = generator.nextDouble() + generator.nextDouble();
System.out.printf("sum = %.4f%n", sum);
// Tip 5: peek at an exception on its way through, then let it continue
try {
try {
order.lineTotal(5);
} catch (Throwable t) {
System.out.println("passing through: " + t);
throw t;
}
} catch (IndexOutOfBoundsException e) {
System.out.println("handled further up");
}
// Tip 6: a stack trace without any exception, captured as a string
var out = new StringWriter();
new Throwable("where am I?").printStackTrace(new PrintWriter(out));
System.out.print(out);
// Tip 8: route uncaught exceptions to your own handler (here: println; normally a logger)
Thread.setDefaultUncaughtExceptionHandler((thread, e) ->
System.out.println("Uncaught exception in " + thread.getName() + ": " + e));
Thread worker = new Thread(() -> { throw new IllegalStateException("worker crashed"); }, "worker-1");
worker.start();
worker.join();
System.out.println("main thread is still running");
}
}
record Item(String name, int quantity, double price) { }
record Order(int id, List<Item> items) {
double lineTotal(int index) {
Item i = items.get(index);
return i.quantity() * i.price();
}
}
class Opaque { }
order=Order[id=1001, items=[Item[name=Widget, quantity=3, price=9.99], Item[name=Gadget, quantity=1, price=24.5]]]
without toString: Opaque@<hash>
nextDouble: 0.7276
nextDouble: 0.6832
sum = 1.4108
passing through: java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 2
handled further up
java.lang.Throwable: where am I?
at Solution.main(Solution.java:38)
Uncaught exception in worker-1: java.lang.IllegalStateException: worker crashed
main thread is still running
Common questions
Should I debug with print statements or a debugger?
Both have their place. A debugger is best for exploring state interactively on your own machine. Logging is better for problems that only occur in production, in timing-sensitive code, or after hours of running, because it leaves a record you can read later. Remove temporary System.out.println calls once you're done. Log statements at DEBUG/FINE level can stay.
Why does my bug disappear when I step through it in the debugger?
That usually points to a race condition or other timing problem. Pausing a thread changes the order in which threads run. Use logging with timestamps and thread names, a thread dump (jcmd <pid> Thread.print), or a JFR recording, all of which disturb timing far less.
Is it safe to leave Java Flight Recorder on in production?
Yes, that's what it was designed for. The default settings cost around one percent of performance. Many teams run a continuous recording with -XX:StartFlightRecording and a maximum age or size, and dump it when something goes wrong.
How do I get a thread dump of a hanging program?
Run jcmd <pid> Thread.print, or jstack <pid>. On Unix you can also send kill -3 <pid>, which prints the dump to the program's standard output. Since Java 21, jcmd <pid> Thread.dump_to_file -format=json file.json also includes virtual threads.
Does -Xlint:all slow down compilation or change the class files?
No. It only enables extra warnings, and the generated bytecode is identical. Add -Werror in CI builds if you want warnings to fail the build.
Summary
- Print or log values freely, and give every class a meaningful
toString. Records do it for you. - Demo
mainmethods,jshelland especially JUnit tests catch bugs early and keep them fixed. - Intercept calls with a logging subclass, or with a dynamic proxy for interfaces.
- Peek at exceptions with catch, print, rethrow. Get a trace anywhere with
Thread.dumpStack()or capture it as a string. - Redirect
System.errwith2>, or both streams with1> file 2>&1. - Log uncaught exceptions with
Thread.setDefaultUncaughtExceptionHandler. -verbose:classand-Xlogshow what the JVM is doing.javac -Xlint:allflags questionable code.- For running programs, use
jcmd(thread dumps, heap info, JFR),jconsole, VisualVM and JDK Mission Control.
Practice Questions
java MyProgram > log.txt leaves the stack traces on the screen. Why, and how do you capture them?
> redirects only standard output, and stack traces go to standard error. Use 2> errors.txt for errors only, or 1> log.txt 2>&1 for both streams in one file.
How can you find out who calls a method, without a debugger and without an exception?
Insert Thread.dumpStack() in the method. It prints the current call stack to System.err. Alternatively, log new Throwable() or use StackWalker.
What happens to other threads when a thread dies from an uncaught exception after you set a default handler?
The handler runs in the dying thread, typically logging the exception, and that thread terminates. Other threads, including main, continue normally.
Your application hangs in production. Which command gives you a first look at what every thread is doing?
jcmd <pid> Thread.print, a thread dump. Threads that are BLOCKED or WAITING on each other point to deadlocks or contention. jconsole can also detect deadlocks.
What does javac -Xlint,-serial do?
It enables all lint warning categories except serial, which warns about serializable classes without a serialVersionUID.
Why is a logging subclass of Random possible, but not of String?
String is final, so it can't be subclassed. Random and its nextDouble method aren't final. For final classes, you have to log at the call sites, or use a proxy if you code against an interface.
Previous: Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
Related reading
- Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
- Java Logging Basics: System.Logger and java.util.logging
- Java Assertions: Using assert, Enabling Assertions and Design by Contract
- Java Exception Handling Best Practices: Tips Every Developer Should Know
- Java finally and try-with-resources: Cleaning Up and Reading Stack Traces

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.