Semicolon at end of 'if' statement Semicolon at end of 'if' statement java java

Semicolon at end of 'if' statement


Why does it happen?

Java Language Specification says that:

The Empty Statement

An empty statement does nothing.

EmptyStatement:    ;

Execution of an empty statement always completes normally

It essentially means that you want to execute empty statement if a==b

if(a == b);

What should you do:

There are two main solutions to this problem:

  1. You can avoid problems with empty statement by using code formatterand surrounding stuff inside if with { and }. By doing thisYour empty statement will be much more readable.

    if(a == b){  ;}
  2. You can also check tools used for static code analysis such as:

    They can instantly highlight problems such as this one.

I would recommend to combine both solutions.


Is there any situation in which this would be useful?

Useful? As in "makes your code cleaner, clearer, faster, more maintainable"? Not at all. This is most likely poor, confusing code.

But it's not necessarily benign. Such a statement can perform actions and/or alter state due to methods which cause side effects, and optionally evaluate those methods due to short-circuiting of operators.

if( a() && b() );

Here, a() or b() may do something, and b() will only execute if a() is true.

As to why, I think the answer is simply that it would be worse to deviate from defined, expected behavior (e.g. statements like while(reader.read());) than the alternative of developers writing bad code.

Writing bad code is always possible. And just to reiterate, this would be bad code in almost any case.


A possible use case:

if (a==b);else {  // Do something}

Not good, but possible.

Still, I do think that the Java specification should disallow an empty if.