Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:
if(a == b);
// Do stuff
Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?
Semicolon at the end of,
if(a==b); simply finish the statement in single line which means ignore the result of condition and continue the execution from the next line
This code is useful, on the other hand sometime introduce bug in program, for example,
case 1.
a = 5;
b = 3;
if(a == b);
prinf("a and b are equal");
case 2.
a = 5;
b = 5;
if(a == b);
prinf("a and b are equal");
would print the same output on the screen...
While working on a programming assignment for class where I am working with a N by N grid of doodads and comparing characteristics of a random doodad to those above, below, left, and right, I found a nice use of this to prevent nested statements and potential boundary exceptions. My goal was to minimize code and keep from nesting if-statements.
where
method(Doodad a, Doodad b)
does some operation between a and b.Alternatively, you could use exception handling to avoid this syntax, but it works and works well for my application.
Just a FYI about the usability and what difference it makes or can make if there is a statement like that
Consider a piece of code like the following.
Clearly in this case, the
if
statement does change the output. So a statement like that can make a difference.This is a situation where this could be useful or better to say have an impact on program.
I can think of a scenario where an empty statement is required (not for
if
condition but forwhile
loop).When a program just want an explicit confirmation from the user to proceed. This may be required when the work after the user confirmation depends on some other things and user want to take control of when to proceed.