ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 33

Updated on October 23, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Lesson 33: How to handle logical errors in Java

As we learnt in Lesson 31, logical errors usually results from poor understanding of the program specification and inaccurate translation of the program algorithm. This type of errors can be difficult and tricky to detect and isolate because unlike syntax errors that are underlined by wavy red lines in Java NetBeans, logical errors are not marked in any way and do not stop the program from executing but when the program run, the results are not what would be expected.

As a beginner programmer, you might have encountered logical errors unknowingly especially because the program usually run without throwing any Exception but if you could have checked the output, most likely they were unexpected. Logical errors can be costly when they occur undetected in a program and a programmer can spend lengthy time trying to locate them.

Source

How to detect, isolate and correct logical errors in Java

In this article, you shall learn how to isolate and correct logical errors using some of the in-built tools found in Java NetBeans. We are going to write a program code and force a logical error.

The program should execute normally but the output will not be as expected. We’ll later use Java NetBeans in-built tools to trace the logical error and correct it. Create a new Java class, type or copy and paste the following code.

This program is supposed to count how many times letter "g" occurs in the word "Debugging". However, when you run the program the output display: "Letter g was found 0 times" so, what could be wrong in the program?

Just to jog your mind, can you spot the logical error is in the program? Probably not but we’ll find out in a minute.

Java program with a logical error

package handleerror;
import javax.swing.JOptionPane;
public class LogicalErrors {
      public static void main(String[] args) {
          int letter_counter = 0;
          String myword = "Debugging";
          String letter = "";
       
          for(int i = 0; i < myword.length(); i++){
             letter = myword.substring( 1,1 );
             if(letter.equals("g")){
                 letter_counter++;
                 
             }
          }
          JOptionPane.showMessageDialog(null,"Letter g was found "+letter_counter+" times");
      }
}
Program output with logical error
Program output with logical error

It is very clear that the program above has an error because the output is not what we expected, however, the program run without throwing Exceptions. This is the hardest part in dealing with logical errors; you don’t have any clue of what could be happening.

Fortunately, Java NetBeans has some in-built tools to help programmers to trace such errors. To start with, we are going to use a tool called Breakpoint at the start of executable statements.

Breakpoint just does as its name suggest; it set a breakpoint in the code to stop execution of the program at that point.

Click on the margins of the code window to add a new Breakpoint at the start of executable statements, in this case at the statement: int letter_counter = 0;

Using Breakpoints in Java
Using Breakpoints in Java

On the Java NetBeans menu bar, Click Debug >> Debug Main Project. (If you have several classes in one project then Right-Click the specific class and select Debug file) Java NetBeans will jump to the Breakpoint and stop code execution at that point. Notice the following new toolbar:

Debugging session toolbar in Java
Debugging session toolbar in Java

The first three buttons on the toolbar allows the programmer to stop the debugging session, pause, and continue the session respectively.

The next five buttons allows the programmer to step into code, step over code, step in or out of code, or jump to the cursor respectively. Alternatively, you can press F5 key to continue. Having Breakpoint in the code does not interfere with the execution of the program in any way.

In the above code, we have a FOR loop that involves three variables; i, letter and letter_counter. We would have expected the variable letter_counter to have a three (3) at the end of the loop as the word “Debugging” has three letters “g” but that is not the case.

What we need to do is to execute the program step by step and keep checking if the loop is working properly and whether actually the letter_counter is being incremented.

On the Java NetBeans menu bar, we are going to add three Watch windows for these three variables. Click on Debug >> New Watch enter variable i as Watch Expression. Repeat this step for the other two variables; letter and letter_counter.

New Watch dialog box
New Watch dialog box

The watches window should look like shown below:

Java debugging Watches window
Java debugging Watches window

Now, click the Step Into icon on the toolbar, alternatively, you can press F7 key on the keyboard.

Showing Step Into icon on the toolbar
Showing Step Into icon on the toolbar

Every time you click on the Step Into icon or press F7 key once, the program execute the next line. Keep pressing the icon or F7 until you enter into the loop. The FOR loop will execute step by step and as it does so keep checking what the variable letter_counter has in every instance of the loop.

The value of variable letter is still empty
The value of variable letter is still empty

Notice on the image above that as the variable i move to value 1 we expect the variable letter to have a string but as you can see on the image, the value of variable letter is still empty. That means the variable counting the number of times i.e. letter_counter cannot move either and that’s why it is still reading a value of zero. That can only mean one thing; that the variable letter_counter is not being incremented and so the following statement has a logical error:

letter = myword.substring(1,1);

Stop the debugging session using the Stop icon.

Showing Stop icon on the toolbar
Showing Stop icon on the toolbar

Change the code with substring() method to this:

letter = myword.substring( i, i + 1 );

Start the debugging session again by pressing the Step into icon. Keep pressing this icon or F7 key like we did before until you finish code execution. This time you will see the values in the variables changing and at the end, you should be able to get the correct output.

The value of variable letter now has string "D"
The value of variable letter now has string "D"
Program output correct result
Program output correct result

So, we have now traced and corrected the logical error that was causing wrong program output. Use of Java in-built tools for tracing and correcting errors such as Breakpoints and Watches can assist a programmer in tracing difficult and tricky errors in a program. In the next lesson, we shall look at how to read a text file in Java.

<< Lesson 32 | Lesson 34 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi teaches12345,

      Always appreciate that you find time to come here, read and comment on my hubs. Thanks a lot.

    • teaches12345 profile image

      Dianna Mendez 

      7 years ago

      Yet another great post! Your expertise continues to amaze me. Very informative and detailed hub. Well done.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)