Debugging Programs

Introduction: Welcome, this page will talk about Debugging a program. When is debugging needed? Whenever a program is not running correctly, freezing, hanging, crashing, giving errors or behaving unexpectedly, it needs to be debugged. Debugging in Java is the process of removing bugs from a script. How to debug: For the purposes of this example, I am going to create a very simple "mistake" of accidentally setting an If statement conditions to the opposite of what they should be. The first thing we need to do is check where the program is actually giving the errors at, to do this, we are going to add a System.out.println line every couple of lines to the script where we think it might be crashing each with a slightly different output string. Like so; (Before Adding Output Lines {Problem Code}:):
  1. boolean debug = false;
  2. if (!debug) {
  3.         debug = !debug;
  4.         debug = !debug;
  5.         debug = !debug;
  6.         debug = !debug;
  7.         debug = !debug;
  8.         if (debug) {
  9.                 System.out.println("YAY");
  10.         }else{
  11.                 System.out.println("Nope");
  12.         }
  13. }
Here is the script after adding the output debugging lines:
  1. boolean debug = false;
  2. System.out.println("Debug 0");
  3. if (!debug) {
  4.         System.out.println("Debug 1");
  5.         debug = !debug;
  6.         System.out.println("Debug 2");
  7.         debug = !debug;
  8.         System.out.println("Debug 3");
  9.         debug = !debug;
  10.         System.out.println("Debug 4");
  11.         debug = !debug;
  12.         System.out.println("Debug 5");
  13.         debug = !debug;
  14.         System.out.println("Debug 6");
  15.         if (debug) {
  16.                 System.out.println("YAY");
  17.         }else{
  18.                 System.out.println("Nope");
  19.         }
  20. }
Debug 0 Debug 1 Debug 2 Debug 3 Debug 4 Debug 5 Debug 6 YAY Now, let's say the problem is that we wanted it to output "Nope" at the end instead of "YAY". We can now analyse that output we got to see that all the code is working ok (because if the program crashed, some outputs would not get output so we could see where it stopped). So we can see all of the outputs except the ending "Nope", so we know everything is working except we have the wrong conditions for our ending if statement, lets change that now. Here is our fixed code:
  1. boolean debug = false;
  2. if (!debug) {
  3.         debug = !debug;
  4.         debug = !debug;
  5.         debug = !debug;
  6.         debug = !debug;
  7.         debug = !debug;
  8.         if (!debug) {
  9.                 System.out.println("YAY");
  10.         }else{
  11.                 System.out.println("Nope");
  12.         }
  13. }
Nope Finished!

Comments

Add new comment