Logic Errors

🙋 Need help? Ask an expert now!

The second of the common errors we will examine is a logic error. Please see below for an example.

package exlcode;

public class LogicErrorExample {
  public static int exampleVariableOne = 5;
  public static int exampleVariableTwo = 10;
  public static int exampleVariableThree = exampleVariableTwo * exampleVariableOne;

  public static void main(String[] args) {
    // this prints the wrong number because the symbol '*' is used instead of the
    // '/'
    System.out.println("10 divided by 5 is " + exampleVariableThree);

The program prints an unexpected value because one of the signs is incorrect in the code. We are looking for the output of 2 but instead see 50 because the multiplication sign is used instead of the division sign. This may seem like a small and avoidable error, but could be missed and difficult to find when dealing with thousands of lines of code and receiving an incorrect output.

Logic errors occur after the program compiles and runs. It can be indicative of a design flaw in the program. Here are some logic errors you may run into: multiplying instead of dividing, adding instead of subtracting and vice versa, or displaying the wrong message. If the program runs and compiles, but the output is incorrect or unexpected, it is a sure sign you have a logic error. Printing different variables and validating their values is one useful way to troubleshoot and solve logic errors.

Edit Me on GitHub!

Application Question

The program suffers a logic error if the _____.