Logic errors in java

hts.StevenWood.com

Common Logic Errors in Java
(run time errors)

Debugging is the process of correcting Run-Time Errors. Debugging is much more difficult than correcting syntax errors because you often don’t know where in the source the error exists. Syntax errors are caught by the complier and therefore the complier can show you where (sometimes exactly where, sometimes approximately where) the error occurs.

Guidelines for Correcting Logic Errors (Run-time Errors)

  1. Avoid the debugging process. Taking the time to write a correct and well-documented program from the start of the programming process will save you time in the long run. Finding and correcting program «bugs» (logic errors) takes a lot of time, and it can be frustrating, especially if you neglected to include code comments
  2. Debug on a small scale. Thoroughly test each component of an application (each method of each object) piece by piece, correcting errors as you go. This is much easier than finding errors in a large program.
  3. Understand the symptom. Before changing a program, understand why the error occurred and where in the program it may have occurred. Look at what the program tried to do and where it went wrong.
  4. Use problem solving techniques to try to determine why an error happened how it could have arisen. Form several hypotheses about how the error might have arisen and explore these possibilities.
  5. Find the source of the error (find the root cause). Don’t waste time making «random» changes to your program. After brainstorming about the cause of the error, you can start searching back through the execution of your program to see where things went wrong.
    A debugger can help.
    1. Examine the call stack and the values of parameters and local variables. See if it matches your expectation of what the program «should» do.
    2. Trace through an execution of your program by hand and with a debugger, stopping at certain points in the execution and/or printing out values along the way.

    The Most Common Logic Errors in Java:

    Using a variable before it is given a value

    This is a common error found in both object-oriented and procedural languages. In Java, primitive variables must be initialized to zero or some default value so there will be no doubt as to what is stored in that variable.

    For Example, the following code . int x;
    x = x + 1;
    System.out.println("X = " + x);

    To fix the problem, initialize the value stored in x to a known value (like 0) .

    Misplaced Semi-colon (usually with a loop or if statement)

    FOR LOOP: for (i=1; i
    System.out.println("Number is " + i);
    >

    The above code will print out "Number is 11" instead of the desired .
    "Number is 1"
    "Number is 2"
    .
    "Number is 10"

    if ( x > y) ;
    System.out.println("X is bigger");
    >

    The above code will print out "X is bigger" regardless of what values are stored in x and y.

    Confusing the equivalence operator == with the assignment operator =

    = = is used to compare two values to see if they are the same while = is used to assign a value to a variable.

    Be careful though, when the = = operator is applied to objects (like stings, arrays, . ) then it compares the addresses of those objects rather than what is stored in those objects.

    For example, the if statement .

    String X1="me"; String X2="me"; if(X1 == X2)

    . will execute the code denoted by the three dots only if the first object occupies the same address as the second object. If the objects occupied different addresses, but still had the same values stored in variables, then the "is statement" would evaluate to false. Unfortunately this does not give rise to any syntax errors, but will show up when any program containing the error is executed.

    Missing the "main" method

    public static void main (String []args)

    For example, if you omit the keyword static then an error message of the form:

    Math: Order of Operation (BEDMAS)

    The Java programming language follows the Mathematic order of operations (BEDMAS) and it is a common programming error to omit brackets when doing math opeartions.

    Forgetting that primitive types (int, double, char . ) are passed by value

    You cannot treat an argument which is a primitive type as if it can be assigned to. This will not be signalled as a syntax error. However, it will show up as a run-time error when you write code which assumes that the scalar has been given a value by a method.

    Forgetting that arguments are passed by reference to methods if they are objects (like Strings and arrays)

    When an object is used as an argument to a method, then its address is passed over and not a value. This means that you can assign values to such arguments. If you treat them as values this will not strictly be an error, but will not be making use of the full facilities of an object-oriented programming language.

    Источник

    Logical Errors in Java

    Book image

    Logical errors in Java programming can be extremely difficult to find because they don’t reflect any sort of coding problem or an error in the use of Java language elements. The code runs perfectly as written — it just isn’t performing the task that you expected it to perform.

    As a result, logical errors can be the hardest errors to find. You need to spend time going through your code looking for a precise reason for the error. Here’s a list of common logical errors that Java developers encounter:

      Using incorrect operator precedence: The order in which Java interprets operators is important. Applications often produce the wrong result because the developer didn’t include parentheses in the correct places. For example, the following example produces outputs of 11, 13, 9, and 8 from the four variables, all due to the location (or lack) of the parentheses.

    public class OperatorError < public static void main(String[] args) < // Create some variables. int MyVar1 = 5 + 4 * 3 / 2; int MyVar2 = (5 + 4) * 3 / 2; int MyVar3 = (5 + 4) * (3 / 2); int MyVar4 = (5 + (4 * 3)) / 2; // Output the result. System.out.println( "MyVar1: " + MyVar1 + "nMyVar2: " + MyVar2 + "nMyVar3: " + MyVar3 + "nMyVar4: " + MyVar4); >>
    public class ForLoopError < public static void main(String[] args) < // Declare the variable. int Count; // Create the loop. for (Count=1; Count> >

    Источник

    Java Guides

    Errors that are detected by the compiler are called syntax errors or compile errors. Syntax errors result from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace without a corresponding closing brace.

    These errors are usually easy to detect because the compiler tells you where they are and what caused them. For example, the following program has a syntax error:

    public class JavaDemo < public static main(String[] args) < System.out.println("Hello World Example); > >

    • The keyword void is missing before main in line 2.
    • The string Hello World Example should be closed with a closing quotation mark in line 3.

    Since a single error will often display many lines of compile errors, it is a good practice to fix errors from the top line and work downward. Fixing errors that occur earlier in the program may also fix additional errors that occur later.

    2. Runtime Errors

    Runtime errors are errors that cause a program to terminate abnormally. They occur while a program is running if the environment detects an operation that is impossible to carry out. Input mistakes typically cause runtime errors. An input error occurs when the program is waiting for the user to enter a value, but the user enters a value that the program cannot handle.

    For instance, if the program expects to read in a number, but instead the user enters a string, this causes data-type errors to occur in the program.

    Another example of runtime errors is division by zero. This happens when the divisor is zero for integer divisions. For instance, the following program would cause a runtime error:

    public class JavaDemo < public static void main(String[] args) < System.out.println(10/0); > >
    Exception in thread "main" java.lang.ArithmeticException: / by zero at com.javaguides.JavaDemo.main(JavaDemo.java:24)

    Logic Errors

    Logic errors occur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example, suppose you wrote the program to convert Celsius 35 degrees to a Fahrenheit degree:

    public class JavaDemo < public static void main(String[] args) < System.out.println("Celsius 35 is Fahrenheit degree "); System.out.println((9 / 5) * 35 + 32); > >
    Celsius 35 is Fahrenheit degree 67 

    You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0. In Java, the division for integers is the quotient—the fractional part is truncated—so in Java 9 / 5 is 1. To get the correct result, you need to use 9.0 / 5, which results in 1.8.

    Common Errors

    Missing a closing brace, missing a semicolon, missing quotation marks for strings, and misspelling names are common errors for new programmers.

    Conclusion

    In general, syntax errors are easy to find and easy to correct because the compiler gives indications as to where the errors came from and why they are wrong. Runtime errors are not difficult to find, either, since the reasons and locations for the errors are displayed on the console when the program aborts. Finding logic errors, on the other hand, can be very challenging.

    Источник

    Читайте также:  Парсинг сообщений телеграмм чатов python
Оцените статью