Java Debugging
π Java Debugging
Debugging is the process of finding and fixing errors (bugs) in a program. Even when the code compiles successfully, it may not produce the expected output β thatβs where debugging comes in.
Java provides multiple ways to debug:
Printing values using
System.out.println()Using debugging tools in IDEs like IntelliJ IDEA, Eclipse, or VS Code
Using exception messages and stack traces
Using breakpoints, step executions, watches, and variable inspection
βοΈ 1. Debugging Using System.out.println()
This is the simplest way to trace values and program flow.
Example:
βοΈ 2. Debugging Using Exceptions & Stack Trace
Java exceptions provide helpful messages to identify runtime issues.
Example (Buggy Code):
π Output:
This tells exactly where and why the program failed.
βοΈ 3. Debugging in IDE Using Breakpoints
Modern IDEs let you:
πΉ Pause program execution (Breakpoint)
πΉ Inspect variable values
πΉ Execute line-by-line (Step Over, Step Into, Step Out)
πΉ Watch expressions and evaluate runtime logic
Steps (Example for IntelliJ/Eclipse):
Click to left of a code line to set a breakpoint
Run program in debug mode
Inspect values and follow execution flow
βοΈ 4. Using Assertions (Debug Mode Only)
Assertions help test assumptions during development.
Example:
π‘ To enable assertion:
βοΈ 5. Common Debugging Tips
| Issue Type | Debugging Technique |
|---|---|
| Wrong output | Print variable values |
| Program crash | Read exception & stack trace |
| Infinite loop | Use breakpoints or debug prints |
| Unexpected behavior | Step through code using IDE |
π§ Example: Debugging a Logical Error
Buggy Code:
Output:
Corrected Code:
Now output:
π― Summary
Debugging in Java helps find and fix logic, syntax, and runtime errors. You can debug using:
| Method | Best Use |
|---|---|
| Print statements | Quick testing |
| Exception messages | Runtime crashes |
| IDE tools | Professional debugging |
| Assertions | Validating assumptions |
