Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 201 ยท Exceptions

Debugging Java Programs

Learn to debug Java - read stack traces and Caused by chains, use helpful NullPointerException messages, print debugging, assertions, debuggers and common bugs.

Every program has bugs; what separates beginners from professionals is how quickly they find them. Debugging is a skill with a method: reproduce the problem, read the evidence the JVM gives you, form a guess, and test the guess with the smallest possible experiment. Staring at code and hoping is not a method.

This lesson teaches the tools in the order you'll reach for them: reading stack traces, Java's helpful NullPointerException messages, print debugging, assertions and the debugger in your IDE. It ends with a gallery of the bugs that trip up almost every Java developer at least once, so you can recognize them on sight.

Read the stack trace from the top

When an exception escapes main, the JVM prints a stack trace: the exception type, its message, and the chain of method calls that was active when it was thrown. Run this program, which fails on purpose:

Java A crash three calls deep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program crashes before it prints anything. The trace looks like this:

TEXT
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2 Size: 2
	at java.base/java.util.ImmutableCollections$AbstractImmutableList.outOfBounds(ImmutableCollections.java:359)
	at java.base/java.util.ImmutableCollections$List12.get(ImmutableCollections.java:612)
	at Main.totalItems(Main.java:9)
	at Main.printReport(Main.java:16)
	at Main.main(Main.java:21)

Read it like this:

  1. First line: what happened. IndexOutOfBoundsException: Index: 2 Size: 2. The message already tells you the bug: someone asked for index 2 of a 2-element list.
  2. Next lines: where. Each at line is a stack frame, newest first. Skip the JDK's own frames (java.base/...) until you reach your code: Main.totalItems(Main.java:9). That's the line to look at.
  3. Below it: how you got there. printReport called totalItems, and main called printReport. If the bug is in the data rather than the method, these frames show you who passed it.

Line 9 is inside a loop with i <= size(): an off-by-one error. Change <= to < and it works.

In our editor, the bottom of a trace sometimes shows a few jdk.compiler/...SourceLauncher frames. Those belong to the launcher that runs single-file programs; ignore them.

Caused by and "... n more"

When code wraps one exception in another (see Custom Exceptions), the trace prints each cause after a Caused by: line. The last Caused by is usually the root problem, and the first one is the high-level description. A line such as ... 6 more means "the remaining 6 frames are the same as in the trace above", printed once to save space.

Java Reading a Caused by chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This one fails on purpose too, after printing pen costs 3. The top line tells you which row is bad; Caused by: java.lang.NumberFormatException: For input string: "4.50" tells you why: parseInt doesn't accept decimals.

Helpful NullPointerException messages

Since Java 14, a NullPointerException explains exactly which reference was null. That turns the most common Java crash into a quick fix:

Java NullPointerException messages that name the culprit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The messages read like sentences: Cannot invoke "Main$Customer.name()" because the return value of "java.util.Map.get(Object)" is null. You know instantly that the map had no entry, not that name was missing.

For local variables, the message names the variable only when the class was compiled with debug information (javac -g, which IDEs, Maven and Gradle use by default). Our editor compiles without it, so locals show up as "<local2>"; fields, array elements and method return values are always named.

The oldest technique still works: print the values you think you know, and compare them with what's actually there. A few habits make it effective:

  • Print to System.err. Debug output stays separate from the real output, and you can find and delete it easily.
  • Label every value. "count=" + count beats a bare 3 in a sea of numbers.
  • Print collections and arrays properly. Lists print themselves; arrays need Arrays.toString (or Arrays.deepToString for 2D).
  • Bisect. Print halfway through the computation. If the value is already wrong there, the bug is in the first half; otherwise it's in the second.
Java Tracing a wrong average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The trace shows sum=17 length=4 (both correct) but result=4.0. So the bug is in the division itself: sum / values.length divides two ints, truncating to 4 before the conversion to double. Fix it with (double) sum / values.length and the program prints 4.25. (See Working with Numbers.)

When you're done, remove the debug prints, or turn the useful ones into proper log statements (Logging).

Assertions

An assertion states something that must be true if your code is correct. If it's false, you have a bug, and the program stops immediately with an AssertionError instead of continuing in a broken state:

Java
assert balance >= 0 : "balance went negative: " + balance;

The part after the colon is the message. Assertions are disabled by default; the JVM skips them entirely unless you start it with -ea (enable assertions):

Terminal
java -ea Main.java          # assertions on
java -ea:com.shop... Main   # only in one package and its subpackages
java Main.java              # assertions off: assert statements do nothing

Our editor runs without -ea. The example below turns assertions on from inside the program for classes loaded afterward, which is a trick for demos, not something you'd do in real code:

Java Assertions catch broken invariants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output starts with assertions in Main: false, then balance: 500, and then the program stops with java.lang.AssertionError: balance went negative: -300. That happens on purpose.

Rules for using assertions well:

  • Check internal assumptions, not user input. Since assertions can be off in production, never use them to validate arguments of public methods or anything a user typed. Throw IllegalArgumentException for that (see Exception Handling Best Practices).
  • No side effects. assert list.remove(x); removes nothing when assertions are off. Compute first, then assert on the result.
  • Good spots: after a tricky calculation, at the end of a method that must keep an invariant, and in default branches that "can't happen".

For checks that must always run, use plain code: if (!condition) throw new IllegalStateException(...).

Using a debugger

Print statements make you guess in advance which values matter. A debugger lets you pause a running program and look at everything. Every Java IDE (IntelliJ IDEA, Eclipse, VS Code with the Java extensions, NetBeans) has one, and they all share the same concepts:

Concept What it does
Breakpoint Pause when execution reaches a line. Click the margin next to the line number.
Conditional breakpoint Pause only when a condition holds, such as i == 999 or name.equals("ana"). Essential inside loops.
Exception breakpoint Pause the moment a given exception (say, NullPointerException) is thrown, before any handler runs.
Step over Run the current line and stop at the next one.
Step into / step out Enter the method called on this line / finish the current method and return to the caller.
Resume Continue until the next breakpoint.
Variables and watches Show local variables, fields and expressions you choose, updated after every step.
Evaluate expression Run any expression in the paused context, like list.size() or order.total() * 2.
Call stack (frames) The same chain as a stack trace, but live: click a frame to see its variables.

A productive routine: set a breakpoint just before the place where things look wrong, run in debug mode, step over line by line and watch which variable first takes a value you didn't expect. That's where the bug is.

The JDK also ships a command-line debugger, jdb, and the JVM can accept a remote debugger, which is how you debug a server running in a container:

Terminal
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar

Your IDE then attaches to port 5005. Our online editor doesn't offer a debugger; use the techniques above here and an IDE on your own machine. The Advanced Java track goes further with profilers and production diagnostics in Debugging and Profiling.

These bugs show up so often that it pays to recognize them instantly. Each one compiles fine and runs without crashing, which is exactly what makes them dangerous:

Java Spot the bug: five classic mistakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  1. == on objects asks "same object?", and a string computed at run time is a different object from the literal. Always compare text with equals (Strings).
  2. Integer caches values from -128 to 127, so == happens to work for small numbers and silently fails for larger ones (Wrapper Classes and Autoboxing).
  3. 1 / 2 is int division, giving 0 before it ever becomes a double.
  4. List<Integer> has both remove(int index) and remove(Object value); an int argument picks the index version. Use ids.remove(Integer.valueOf(3)) to remove by value.
  5. String methods return a new string. Calling strip() without using the result does nothing.

Others to keep on your list: = instead of == in a condition with booleans (if (done = true) always runs), missing break in a classic switch (fall-through, see switch), overriding equals without hashCode (The Object Class), and changing a collection while looping over it with for-each (ConcurrentModificationException).

A debugging routine

When you're stuck, go through these steps in order:

  1. Reproduce it reliably. Find the smallest input that triggers the bug. A bug you can trigger on demand is half fixed.
  2. Read the message and the first frame in your code. Most crashes are explained right there.
  3. State what you expected and what happened. Writing it down (or explaining it to a colleague) often reveals the wrong assumption.
  4. Narrow it down. Bisect with prints or breakpoints until you find the first wrong value.
  5. Fix the cause, not the symptom. A null check that hides a missing value just moves the bug.
  6. Keep it fixed. Turn the failing case into a unit test (Unit Testing with JUnit) so it can never quietly return.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a stack trace, which line usually points at the code you should look at first?

    Frames are listed newest first. JDK frames at the top show where the library noticed the problem; the first frame in your code is where your program made the bad call.
  2. 2. What does double r = 7 / 2; System.out.println(r); print?

    7 / 2 is int division and gives 3. Only then is 3 widened to the double 3.0.
  3. 3. You run java Main.java and the code contains assert count > 0; while count is 0. What happens?

    Assertions are off by default. The JVM skips assert statements entirely unless they are enabled with -ea.
  4. 4. A trace ends with Caused by: java.lang.NumberFormatException: For input string: "12a". What does that tell you?

    Caused by lists the wrapped (original) exception. The last Caused by in a trace is usually the root problem.
  5. 5. Which line removes the value 5 (not the element at index 5) from a List<Integer> nums?

    An int argument selects remove(int index). Passing an Integer object selects remove(Object), which removes by value.

Summary

  • Read a stack trace top-down: the first line says what happened; the first frame in your code says where; frames below show how you got there.
  • Caused by: lists wrapped exceptions; the last one is usually the root cause, and ... n more marks repeated frames.
  • Helpful NullPointerException messages (Java 14+) name the null field, method result or array element.
  • Print debugging works best with labeled values on System.err and bisecting the computation.
  • assert checks internal invariants and runs only with -ea; never use it for input validation or with side effects.
  • Debuggers pause programs at breakpoints and let you step through code and inspect any value.
  • Know the classics on sight: == on strings and wrappers, integer division, remove(int) vs remove(Object), ignored return values, off-by-one loops.

Next: Wrapper Classes and Autoboxing, where you'll learn how primitives become objects, and why == on an Integer can surprise you.