1

Possible Duplicate:
semicolon at end of if statement

I was programming, and found a bug in my code, and it was because of a semi colon after an "if" statement, and its boxy "{ xxx }" was being executed as if it has its own scope -- so everything would get compiled.

This begs the question, why is:

if (x != null);

A possible statement in Java, it seems like a useless line of code that could generate lots of bugs, etc.

4

2 回答 2

3

该行基本上等同于:

if (x != null) {
}

但是,您可以创建如下行:

if (x != null) System.out.println(x);

所以它的存在是为了支持这种代码的执行,但你的例子只是我第一个例子的简写。

于 2013-01-20T21:31:26.873 回答
0

从我所看到的(我可能错了)只有一个理由做这样的事情。

想象一下x是一个 getter,然后x从当前类中获取变量,然后执行另一段代码(或者可能只是缓存 的响应x)。

也就是说,如果是这样的话,我认为x;也可以。

于 2013-01-20T21:31:44.770 回答