Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do java if statement fail when it ends in semicolon [duplicate]

Tags:

java

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?

like image 797
Uchenna Nwanyanwu Avatar asked Oct 07 '12 19:10

Uchenna Nwanyanwu


1 Answers

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

like image 165
Tomasz Nurkiewicz Avatar answered Sep 20 '22 18:09

Tomasz Nurkiewicz