且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么java if语句在以分号结尾时失败

更新时间:2022-06-16 09:22:07

这个分号结束一个语句(一个空的),所以你的代码由编译器翻译成类似这样的事情:

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");
}

换句话说,如果 if 表达式是 true ,它执行空代码块。然后,无论 是否为真,运行时都会继续并运行包含 System.out 的块。空语句仍然是一个语句,所以编译器接受你的代码。

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

好的IDE应该立即警告你这样的陈述,因为它可能永远不会正确(如 if(x = 7)在某些语言中)。

Good IDE should immediately warn you about such statement as it's probably never correct (like if(x = 7) in some languages).