Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Logic Errors
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
The second of the common errors we will examine is a logic error. Please see below for an example.
LogicErrorExample.java
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.