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:

public class DebugExample {
public static void main(String[] args) {
int num = 5;
int result = num * 2;
System.out.println(“Value of result: “ + result); // Debug print

result += 10;
System.out.println(“Updated result: “ + result); // Debug print
}
}


βœ”οΈ 2. Debugging Using Exceptions & Stack Trace

Java exceptions provide helpful messages to identify runtime issues.

Example (Buggy Code):

public class DivideExample {
public static void main(String[] args) {
int num = 10;
int divider = 0;
int result = num / divider; // Causes ArithmeticException
System.out.println(result);
}
}

πŸ›‘ Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

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):

  1. Click to left of a code line to set a breakpoint

  2. Run program in debug mode

  3. Inspect values and follow execution flow


βœ”οΈ 4. Using Assertions (Debug Mode Only)

Assertions help test assumptions during development.

Example:

public class AssertionDebug {
public static void main(String[] args) {
int age = 15;
assert age >= 18 : “Age must be 18 or older”;

System.out.println(“Age: “ + age);
}
}

πŸ’‘ To enable assertion:

java -ea AssertionDebug

βœ”οΈ 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:

public class SumDebug {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + 1; // BUG: should be sum + i
}

System.out.println(“Sum = “ + sum);
}
}

Output:

Sum = 5

Corrected Code:

sum = sum + i;

Now output:

Sum = 15

🎯 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

You may also like...