- Computers & Software
Java Debugging Tip: The Empty Statement
A Java program might build properly but still contain a subtle logic error called an Empty Statement. The Empty Statement isn't serious enough to generate a syntax error. However, it's devious enough to cause frustration during the development process. In this tutorial we investigate the potential problems caused by Empty Statements and how to avoid them.
Consider the following example in Figure 01. The simple for loop should print 100 lines as i is incremented from 0 to 99. Unfortunately, an extra semi-colon lurks just beyond the closing parenthesis. This is a classic example of a logic error.
The semi-colon terminates the loop. The output statement might appear to be part of the loop because it's indented, but it's not. Indenting provides only a visual cue for programmers.
We do get several visual cues that are easliy ignored, especially if the program is large and complicated. The suspicious line of code is underlined with a dreaded NetBeans squiggle and the margin is tagged with a warning icon. For better or worse, these cues are purely advisory; they do not prevent the program from building or executing.
Hovering the mouse over the line of code or the margin tag also brings up a related message.
In the following figure we see that the program builds with no errors or warnings. That's all most programmers need to know. If it built, it must be ready to run. :)
In the following figure we see that the program executes, although probably not as intended. The Empty Statement terminated the for loop and the print statement executed only once.
If you didn't know what the program was supposed to do, this error might slip past.
Knowing what the program is supposed to do, it's easy to identify the problem in such a small chunk of code. However, knowing how to spot the warning signs provided by NetBeans will save you a lot of time in the long run.
In Figure 04, below, the offending semi colon has been deleted and the program runs very differently.
Will braces solve the problem? Nope. The semi colon still terminates the loop, as illustrated in Figure 05. Interestingly enough, the braces do nothing at all. One wonders why Netbeans declines to warn about it.
Figure 06, below, illustrates the output of the program after adding the braces and leaving in the rogue semi colon.