I made a coding mistake while working on an application, it was a test for null reference. It took me hours to discover what the issue was, but what i don't understand is why the code behaved this way.
String name = null;
String value = null;
if(name != null && value != null);
{
System.out.println("Values not null");
}
The if Statement ended with ;
, that was my mistake and the Values not null
was printed even when it is obvious that both values are null. Can anybody explain why?
This semicolon ends a statement (an empty one), so your code is translated by the compiler to something like this:
if(name != null && value != null)
{
//nothing here
}
{
System.out.println("Values not null");
}
In other words, if if
expression is true
, it executes empty block of code. Then no matter whether if
was true or not, the runtime proceeds and runs the block containing System.out
. Empty statement is still a statement, so the compiler accepts your code.
Another place where such a mistake can happen:
for(int i = 0; i < 10; ++i);
{
System.out.println("Y U always run once?");
}
or even worse (infinite loop):
boolean stop = false;
while(!stop);
{
//...
stop = true;
}
It took me hours to discover what the issue was
Good IDE should immediately warn you about such statement as it's probably never correct (like if(x = 7)
in some languages).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With