为什么java if语句在以分号结尾时失败 [英] Why do java if statement fail when it ends in semicolon
问题描述
我在处理应用程序时犯了编码错误,这是对空引用的测试。我花了几个小时才发现问题是什么,但我不明白的是代码表现的原因。
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");
}
if语句以结尾;
,这是我的错误,并且值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?
推荐答案
这个分号结束一个语句(一个空的),所以你的代码由编译器翻译成类似这样的事情:
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).
这篇关于为什么java if语句在以分号结尾时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!