One thing that you are going to notice as you learn about programming is that you tend to make a fair number of mistakes and assumptions that cause your program to either: 1) not compile, or 2) produce output that you don't expect when it executes. These problems are referred to as bugs, and the act of removing them is called debugging. About half of the time of any programmer is spent debugging.

You will have plenty of time and opportunity to create your own bugs, but to get more familiar with the possibilities let's create a few. In your program, try erasing one of the semicolons at the end of a line and try compiling the program with javac. The compiler will give you an error message. This is called a compiler error, and you have to eliminate all of them before you can execute your program. Try misspelling a function name, leaving out a "{" or eliminating one of the import lines to get used to different compiler errors. The first time you see a certain type of compiler error it can be frustrating, but by experimenting like this -- with known errors that you create on purpose -- you can get familiar with many of the common errors.

A bug, also known as an execution (or run-time) error, occurs when the program compiles fine and runs, but then does not produce the output you planned on it producing. For example, this code produces a red rectangle with two diagonal lines across it:

        g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);

The following code, on the other hand, produces just the red rectangle (which covers over the two lines):

        g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);

The code is almost exactly the same but looks completely different when it executes. If you are expecting to see two diagonal lines, then the code in the second case contains a bug.

Here's another example:

        g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);

This code produces a black outlined box and two diagonals. This next piece of code produces only one diagonal:

        g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(0, 200, 0, 200);

Again, if you expected to see two diagonals, then the second piece of code contains a bug (look at the second piece of code until you understand what went wrong). This sort of bug can take a long time to find because it is subtle.

You will have plenty of time to practice finding your own bugs. The average programmer spends about half of his or her time tracking down, finding and eliminating bugs. Try not to get frustrated when they occur -- they are a normal part of programming life.

0 comments