Why does a Java if statement fail when it ends in semicolon [duplicate]

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).

Leave a Comment