Test and debug the program
Having written the program, the next job is to test it to find out whether it is doing its intended job. Testing a program involves the following steps:
1. compile the program: recall that a computer can execute a program written in machine language only. Before the computer can run our Java program, the latter must be converted to machine language. We say that the source code must be converted to object code or machine code. (Note, however, that Java does not produce machine code directly. It converts Java source code into something called Java bytecode. This bytecode is executed (we say interpreted) by another program called the Java interpreter. We will get to details later.)
The program which does this job is called a compiler. Among other things, a compiler will check the source code for syntax errors—errors which arise from breaking the rules for writing statements in the language. For example, a common syntax error in writing Java programs is to omit a semicolon or to put one where it is not required.
If the program contains syntax errors, these must be corrected before compiling it again. When the program is free from syntax errors, the compiler will convert it to machine language (bytecode in Java) and we can go on to the next step.
2. run the program: here we request the computer to execute the program and we supply data to the program for which we know the answer. Such data is called test data. Some values we can use for the length of a side are 3, 12 and 20.
If the program does not give us the answers 9, 144 and 400, respectively, then we know that the program contains at least one logic error. A logic error is one which causes a program to give incorrect results for valid data. A logic error may also cause a program to crash (come to an abrupt halt).
If a program contains logic errors, we must debug the program—we must find and correct any errors that are causing the program to produce wrong answers.
To illustrate, suppose the statement which calculates the area was written (incorrectly) as:
a = s + s;
and when the program is run, 10 is entered for the length. Assume we know that the area should be 100. But when we run the program, we get
Enter length of side: 10
Area of square is 20
Since this is not the answer we expect, we know that there is an error (perhaps more than one) in the program. Since the area is wrong, the logical place to start looking for the error is in the statement which calculates the area. If we look closely, we should discover that + was typed instead of *. When this correction is made, the program works fine.