Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

java - Semicolon at end of 'if' statement

Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:

if(a == b);
// Do stuff

Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 formatter and surrounding stuff inside if with { and }. By doing this Your 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...