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:
In other words, if
ifexpression istrue, it executes empty block of code. Then no matter whetherifwas true or not, the runtime proceeds and runs the block containingSystem.out. Empty statement is still a statement, so the compiler accepts your code.Another place where such a mistake can happen:
or even worse (infinite loop):
Good IDE should immediately warn you about such statement as it’s probably never correct (like
if(x = 7)in some languages).