In the previous lesson you learnt how to create objects.


Dealing with errors

Errors in Java programs can be categorised into two types:

  1. Errors that stop the class from being compiled.
  2. Errors where the program compiles successfully but does the wrong thing when it runs.


There are two categories of reason why a class won't compile: syntax errors and semantic errors:

// Example syntax error - missing semi-colon at end of statement
Date today = new Date()

// Example semantic error - should be getTime() not getTimes()
int time = today.getTimes();
 

To resolve a syntax or semantic error you need to look at the message(s) provided by the compiler. It is generally caused by a typing error or spelling mistake.

Errors where the class compiles but does the wrong thing when run are known as logical errors:

// Example logical error – should be adding not subtracting
int numberOfMen = 7;
int numberOfWomen = 5;
int total = numberOfMen – numberOfWomen; // should use + not -
 

To resolve a logical error is often harder, and you may have to trace through each statement to spot where it is going wrong. See if you can spot the error in the following method:

// This method should return a value that is twice the product
// of the three arguments
public int twiceProduct(int firstNumber, int secondNumber,
						 	  int thirdNumber) {
	// Add the three argument values
	int sum = firstNumber + secondNumber + thirdNumber;

	// double the sum just calculated
	int twiceSum = sum * 3; // * means multiply
	return twiceSum;
}
 

Hopefully you can see that the sum is being multiplied by 3 when it should instead be multiplied by 2. If you are unable to spot the logical error by just looking at the code, then a good technique is to send pertinent values to output at particular stages using System.out.println():

// This method should return a value that is twice the product
// of the three arguments
public int twiceProduct(int firstNumber, int secondNumber,
							   int thirdNumber) {
	// Add the three argument values
	int sum = firstNumber + secondNumber + thirdNumber;
	System.out.println(“sum = “ + sum);

	// double the sum just calculated
	int twiceSum = sum * 3; // * means multiply
	System.out.println(“ twiceSum = “ + twiceSum);

	return twiceSum;
}
 

Doing the above should help you locate where the error is, since you will see that sum is correct but twiceSum is incorrect, so you only need to look at the line(s) of code that precede the incorrect location.

A logical error in a piece of software is known as a bug, so resolving errors is known as debugging. There are more sophisticated debugging techniques involving breakpoints and assertions, which will be covered later in the course.


In the next lesson you will see how to use the provided Java APIs.

Lesson 2.4 Java APIs