Java Debugging Tutorial
100%

Java Debugging Tutorial

Debugging is the process of finding, understanding, and fixing errors in a program. Java developers use debugging techniques and tools to identify why a program is not working as expected.

1. What Is Debugging?

Debugging means examining a program to find the cause of a problem and correcting it.

For example, consider this program:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

        int result = a / b;

        System.out.println(result);
    }
}

This program attempts to divide an integer by zero.

Error: Java throws an ArithmeticException when integer division by zero occurs.

Corrected version:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 2;

        int result = a / b;

        System.out.println(result);
    }
}
Output: 5

2. Types of Errors in Java

Java programs commonly encounter these types of errors:

Error Type Description Example
Syntax Error Code violates Java syntax rules. Missing semicolon.
Compile-Time Error The compiler cannot compile the code. Using an undeclared variable.
Runtime Error An error occurs while the program is running. Integer division by zero.
Logical Error The program runs but produces an incorrect result. Using addition instead of multiplication.
Example of a Syntax Error
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}

The statement is missing a semicolon.

Correct Code
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}
Example of a Logical Error
public class Main {
    public static void main(String[] args) {
        int length = 10;
        int width = 5;

        int area = length + width;

        System.out.println("Area: " + area);
    }
}

The program compiles and runs, but the formula is incorrect. The area of a rectangle is calculated by multiplying length by width.

int area = length * width;
Correct Output: Area: 50

3. Using System.out.println() for Debugging

One of the simplest debugging techniques is printing variable values and messages using System.out.println().

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        System.out.println("Value of a: " + a);
        System.out.println("Value of b: " + b);

        int result = a * b;

        System.out.println("Result: " + result);
    }
}
Output
Value of a: 10
Value of b: 5
Result: 50

These messages help you check whether variables contain the expected values and whether the program follows the expected steps.

Tip: Use descriptive messages so you can understand which value or operation you are checking.

4. What Is a Breakpoint?

A breakpoint is a marker placed on a line of code where a debugger should pause program execution.

Breakpoints allow you to:

  • Pause program execution.
  • Inspect variable values.
  • Check which line will execute next.
  • Find the location where a problem occurs.
Example
public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        int sum = a + b;

        System.out.println(sum);
    }
}

You can place a breakpoint on the line int sum = a + b; in your IDE. When the debugger reaches that line, execution pauses before the statement runs.

Note: Breakpoints are set inside a debugger, such as the one in IntelliJ IDEA, Eclipse, or Visual Studio Code with suitable Java debugging support.

5. Step Over, Step Into, and Step Out

Debuggers provide controls for executing code step by step.

Command Meaning
Step Over Executes the current line without entering a called method.
Step Into Enters a method called by the current statement, when possible.
Step Out Continues execution until the current method returns.
Continue Resumes execution until another breakpoint or stopping condition.
Example
public class Main {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(10, 20);

        System.out.println(result);
    }
}

If you pause at add(10, 20), Step Into can take you into the add() method. Step Over executes the call without opening the method's code.

6. Inspecting Variables

A debugger lets you inspect the values stored in variables while a program is paused.

public class Main {
    public static void main(String[] args) {
        int price = 100;
        int quantity = 3;

        int total = price * quantity;

        System.out.println("Total: " + total);
    }
}

When debugging, inspect these variables:

Variable Expected Value
price 100
quantity 3
total 300

If total contains an unexpected value, inspect the calculation and the values of its input variables.

7. Debugging a NullPointerException

A NullPointerException can occur when code attempts to use an object reference that is null in a way that requires an actual object.

Incorrect Code
public class Main {
    public static void main(String[] args) {
        String name = null;

        System.out.println(name.length());
    }
}

The program throws a NullPointerException because name does not refer to a String object.

Corrected Code
public class Main {
    public static void main(String[] args) {
        String name = null;

        if (name != null) {
            System.out.println(name.length());
        } else {
            System.out.println("Name is not available.");
        }
    }
}
Output
Name is not available.

When debugging a null reference problem, check where the reference is assigned and whether it can be null before use.

8. Reading a Stack Trace

A stack trace provides information about an exception and the sequence of method calls leading to it.

Example Error
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:5)

Important parts of this message:

  • ArithmeticException identifies the exception type.
  • / by zero describes the problem.
  • Main.java:5 identifies the source file and line where the exception was reported.
Tip: Read the exception message first, then inspect the relevant source line and the values used there.

9. Debugging in an IDE

An Integrated Development Environment (IDE) provides tools to compile, run, and debug Java programs.

Common Java development environments include:

  • IntelliJ IDEA
  • Eclipse
  • Visual Studio Code with Java extensions
  • NetBeans
General Debugging Steps
  1. Open your Java project.
  2. Find the line where you suspect the problem occurs.
  3. Set a breakpoint on that line.
  4. Start the program using the debugger.
  5. Inspect variables when execution pauses.
  6. Use Step Over or Step Into to follow execution.
  7. Correct the problem and run the program again.
The exact buttons and menus vary between IDEs, but the basic debugging process is similar.

10. Using Assertions for Debugging

An assertion checks whether a condition is true. It can help detect unexpected program states during development.

public class Main {
    public static void main(String[] args) {
        int age = 20;

        assert age >= 0 : "Age cannot be negative";

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

If the assertion condition is false and assertions are enabled, Java throws an AssertionError.

Enable assertions when running the program:

java -ea Main
Important: Assertions are normally disabled unless enabled with -ea. Do not use assertions to validate essential user input or enforce security checks.

11. A Systematic Debugging Process

  1. Reproduce the problem: Find a reliable way to make the error occur.
  2. Read the error message: Identify the exception or incorrect result.
  3. Locate the relevant code: Inspect the reported line or calculation.
  4. Check the inputs: Verify variable values and method arguments.
  5. Form a hypothesis: Identify a possible cause.
  6. Test the cause: Use breakpoints, logs, or a small test case.
  7. Fix the problem: Change the code responsible for the issue.
  8. Test again: Confirm the fix and check related cases.
Best Practice: Try to understand the cause of an error instead of changing code randomly.

12. Practice Assignments

  1. Find and fix a missing semicolon in a Java program.
  2. Correct a program that uses an undeclared variable.
  3. Fix a program that divides an integer by zero.
  4. Find a logical error in a rectangle area calculation.
  5. Use System.out.println() to inspect variable values.
  6. Create a breakpoint and inspect variables in your IDE.
  7. Fix a NullPointerException in a String example.
  8. Read a stack trace and identify the reported source line.
  9. Use Step Over and Step Into in a method example.
  10. Write a program with an assertion and run it with -ea.

Java Debugging - Quick Quiz

Choose the correct answer for each question.

1. What is debugging?



2. What does a breakpoint do?



3. Which exception can occur when calling a method on a null reference?