Java编译行为
在下面的代码中,为什么没有最后一个 return 语句就无法编译。
private boolean fileExists(final File[] files, final String name) {
if (files == null || files.length == 0) {
return false;
}
for (final File file : files) {
return true;
}
return false; // why is this neessary?
}
In the code below, why it does not compile without the last return statement.
private boolean fileExists(final File[] files, final String name) {
if (files == null || files.length == 0) {
return false;
}
for (final File file : files) {
return true;
}
return false; // why is this neessary?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果
files
为空,则不会进入循环,但该函数需要返回一个boolean
。这就是为什么If
files
is empty you don't enter the loop but the function need to return aboolean
. That's why因为如果
files
为空会发生什么?对于这种情况,您需要第二个 return 语句。
Because what happens if
files
is empty?You need the second return statement for that case.
因为
files
可能是空的。该方法必须在签名中定义的所有情况下返回布尔值!because
files
could have been empty. The method must return a boolean value in all cases as defined in the signature!如果
files
为空(毕竟编译器不知道),则不会返回任何内容。If
files
is empty (the compiler doesn't know, after all) then nothing would be returned.因为您声明该方法返回一个布尔值
如果您不希望它返回任何内容,则将该方法声明为“void”
您可能确实需要“return”,因为如果两个“if”语句都为假会发生什么?
Because you declared that the method returns a boolean value
If you dont want it to return anything then declare the method as 'void'
You probably do need the 'return' because what happens if both 'if' statements are false?
如果
if
和for
中的return
没有执行,我们仍然需要返回一个值。因此需要一个return
语句。查看代码,我们发现
if
中的 return 或for
中的 return 将会被命中,但这不能被编译器推断出来。If the
return
insideif
andfor
are not executed we still need to return a value. So areturn
statement is required.Looking at the code we see that either the return in the
if
or thefor
will be hit, but this cannot be inferred by the compiler.